我试图打开游标到MySQL-DB。但我发现了这个错误:Python:MySQL连接已打开,但无法创建光标
'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 2013-04-24 14:59:29
@Vyktor:我增加了一些代码。 – Joko 2013-04-24 15:04:18
@eandersson不,你错了。你应该**总是**手动关闭光标。否则你会得到内存泄漏。 – Vyktor 2013-04-24 15:08:38