【问题标题】:Python: MySQL connection is open, but can't create cursorPython:MySQL 连接已打开,但无法创建游标
【发布时间】:2013-04-24 14:49:58
【问题描述】:

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

'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 ... 连接已打开。

如果我在“连接”函数中创建游标和 SQL 语句,一切正常。

奇怪的是,一切看起来都是正确的,并且对于具有相同功能的其他一些连接,一切也都运行良好。我不知道如何解决这个错误。我希望有人能指出我正确的方向。

【问题讨论】:

  • 您确定没有遗漏一些重要的代码吗?是不是可能是另一行出错了,或者你不小心把它放到了不同的对象中?
  • @Vyktor:我添加了更多代码。
  • @eandersson 不,你错了。您应该始终手动关闭光标。否则会导致内存泄漏。
  • 你能告诉我们你如何调用函数connectsetValue吗?
  • @Vyktor 我的错,没想到那一个通过正确。

标签: python mysql mysql-python


【解决方案1】:

我会将检查连接是否打开的语句更改为检查 conn 是否为 none 以及连接是否打开。而且因为您总是执行setValue 函数,我建议您在__init__ 函数中调用connect。

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 连接器,您需要在执行插入或更新语句后调用 commit。

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

【讨论】:

  • 我不认为这是问题所在。我只连接一次。
  • 如果有不同的问题,它不会显示在您附加的代码中。考虑向我们展示更多您的代码。
  • 很遗憾,它不起作用,因为连接上方的一行是打开的。
  • @Joko 如果上面的代码不起作用,问题可能是上面代码中没有显示的东西。
  • 我想知道,为什么如果我在 'connect' 函数中运行 cmets 中的代码一切正常。
猜你喜欢
  • 1970-01-01
  • 2012-06-09
  • 1970-01-01
  • 1970-01-01
  • 2015-11-15
  • 2011-09-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多