Skip to content Skip to sidebar Skip to footer

Python: Mysql Connection Is Open, But Can't Create Cursor

I'm trying to open a cursor to a MySQL-DB. But I'm getting this error: 'NoneType' object has no attribute 'cursor' Here is a small sourcecode: class Sample: def __init__(self):

Solution 1:

I would change the statement that checks if the connection is open to both check if conn is none as well as if the connection is open. And because you always execute the setValue function I would recommend that you call the connect inside the__init__ function.

classSample:
  conn = Nonedef__init__(self):
    self.connect()
    self.value = self.setValue()
    self.close()

  defconnect(self):
    self.conn = MySQLdb.connect(...)

  defclose(self):
    if self.conn:
       self.conn.close()

  defsetValue(self):
    ifnot self.conn andnot self.conn.open:
       self.connect()
    cursor = self.conn.cursor()

Also, remember that with the Python MySQL Connector you need to call commit after you execute a insert or update statement.

cur =  self.conn.cursor()
cur.execute("...")
self.conn.commit()

Post a Comment for "Python: Mysql Connection Is Open, But Can't Create Cursor"