Python: MySQL connection is open, but can't create cursor

╄→гoц情女王★ 提交于 2019-12-11 00:05:30

问题


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):
    self.conn = None
    self.value = self.setValue()

  def connect(self):
    self.conn = MySQLdb.connect(...)
    #cursor = self.conn.cursor()
    #cursor.execute("SELECT ...")
    #value = str(cursor.fetchone()[0])
    #raise Exception(value)
    #cursor.close() <- here everything is working fine

  def setValue(self):
    if (self.conn == None):
    self.connect()      
    #raise Exception(self.conn.open)
    cursor = self.conn.cursor() # ERROR: 'NoneType' object has no attribute 'cursor'
    ...

If I use the exception I get a 1 ... connection is open.

And if I do the cursor creation and the SQL statement in the 'connect' function everything is working well.

The strange this is, everything looks correct and for some other connections with the same functions everything is working well, too. I don't know how to solve this error. I hope someone can point me in the right direction.


回答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.

class Sample:
  conn = None

  def __init__(self):
    self.connect()
    self.value = self.setValue()
    self.close()

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

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

  def setValue(self):
    if not self.conn and not 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()


来源:https://stackoverflow.com/questions/16195118/python-mysql-connection-is-open-but-cant-create-cursor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!