[英]Python: MySQL connection is open, but can't create cursor
我正在嘗試打開一個指向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 ...連接已打開。
如果我在'connect'函數中執行了游標創建和SQL語句,則一切運行正常。
奇怪的是,一切看起來都是正確的,並且對於具有相同功能的某些其他連接,一切也都運行良好。 我不知道如何解決這個錯誤。 我希望有人能指出我正確的方向。
我將更改檢查連接是否打開的語句,以檢查conn是否為空以及連接是否打開。 並且因為您總是執行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 Connector,您需要在執行插入或更新語句后調用commit。
cur = self.conn.cursor()
cur.execute("...")
self.conn.commit()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.