2013-04-24 68 views
2

我试图打开游标到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语句,那么一切都运行良好。

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

+1

你确定你不错过一些重要的代码吗?难道这不可能是另一条线上的错误,或者你把它意外地放到了不同的对象中? – Vyktor 2013-04-24 14:59:29

+0

@Vyktor:我增加了一些代码。 – Joko 2013-04-24 15:04:18

+0

@eandersson不,你错了。你应该**总是**手动关闭光标。否则你会得到内存泄漏。 – Vyktor 2013-04-24 15:08:38

回答

0

我会更改检查连接是否打开的语句,以检查conn是否为none以及连接是否打开。因为你总是执行setValue函数,所以我建议你调用__init__函数内的连接。

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你执行一个INSERT或UPDATE语句之后。

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

我不认为这是问题。我只连接一次。 – Joko 2013-04-24 14:58:25

+0

如果存在不同的问题,它不会显示在您附加的代码中。考虑向我们展示更多你的代码。 – eandersson 2013-04-24 15:01:33

+0

@Joko尝试使用我在答案末尾添加的代码。 – eandersson 2013-04-24 15:04:19