Python:MySQL连接已打开,但无法创建游标 [英] Python: MySQL connection is open, but can't create cursor

查看:239
本文介绍了Python:MySQL连接已打开,但无法创建游标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试打开一个指向MySQL-DB的游标.但是我遇到了这个错误:

I'm trying to open a cursor to a MySQL-DB. But I'm getting this error:

'NoneType' object has no attribute 'cursor'

这是一个小的源代码:

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'
    ...

如果使用异常,则得到1 ...连接已打开.

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

如果我执行游标创建和'connect'函数中的SQL语句,一切将正常工作.

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.

推荐答案

我将检查连接是否打开的语句更改为conn不存在以及连接是否打开.并且因为您总是执行setValue函数,所以我建议您在__init__函数内部调用connect.

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()

此外,请记住,在执行插入或更新语句后,需要使用Python MySQL Connector调用commit.

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()

这篇关于Python:MySQL连接已打开,但无法创建游标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆