【发布时间】: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 不,你错了。您应该始终手动关闭光标。否则会导致内存泄漏。
-
你能告诉我们你如何调用函数
connect和setValue吗? -
@Vyktor 我的错,没想到那一个通过正确。
标签: python mysql mysql-python