2015-01-09 41 views
0

我有一個Python腳本,得到我的MySQL版本,但我不斷收到同樣的錯誤「_mysql_exceptions.InterfaceError:(0,‘’)」Python的MySQL的遊標會關閉連接

我去python2.7控制檯並試圖相同,

import MySQLdb 
conn = MySQLdb.connect (host="localhost",user="user", passwd="pass", db="example") 
cursor = conn.cursor() 
cursor.execute ("SELECT VERSION()") 

Traceback (most recent call last): File "", line 1, in
File "/usr/local/lib/python2.7/site-packages/MySQLdb/cursors.py", line 205, in execute self.errorhandler(self, exc, value) File "/usr/local/lib/python2.7/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler raise errorclass, errorvalue _mysql_exceptions.InterfaceError: (0, '')

和文件

import sys 
import MySQLdb 
try: 
    conn = MySQLdb.connect (host="localhost",user="user", passwd="pass", db="example") 
except MySQLdb.Error, e: 
    print "Error %d: %s" % (e.args[0], e.args[1]) 
    sys.exit (1) 
try: 
    cursor = conn.cursor() 
    cursor.execute ("SELECT VERSION()") 
    row = cursor.fetchone() 
    print "server version:", row[0] 
    cursor.close() 
except MySQLdb.Error, e: 
    print "Error %d: %s" % (e.args[0], e.args[1]) 
    #sys.exit (1) 
conn.close() 

[用戶@本地] $蟒蛇b.py

Error 0: Traceback (most recent call last): File "b.py", line 18, in conn.close() _mysql_exceptions.ProgrammingError: closing a closed connection

感謝

回答

1

縮進第二conn.close(),否則你關閉一個成功的查詢後關閉的連接。

+0

如果我縮進第二個conn.close()它仍然不顯示版本,並且它給出了相同的錯誤 – 2015-01-10 18:38:55

+0

對不起......用新鮮的眼睛看這個,現在理解調試b.py不是你的客觀,但理解你的連接問題是。 – dylrei 2015-01-10 18:59:57

+0

我的猜測是連接因爲某種原因在內部關閉。如果在第二個「嘗試」塊之前「打印conn.open」,會發生什麼? – dylrei 2015-01-10 19:04:58

2

如果您的try塊成功運行,那麼您將關閉連接兩次。我想你可以把它放在最後擋住,這將解決你的問題。