El_Feto
El_Feto

Reputation: 43

Python mysql cursor closes connection

I have a python script that gets my mysql version, But I keep getting the same error "_mysql_exceptions.InterfaceError: (0, '')"

I went to the python2.7 console and tried the same,

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, '')

and the file

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 ()

[user@localhost]$ python b.py

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

Thanks

Upvotes: 0

Views: 5513

Answers (2)

dinesh.kumar
dinesh.kumar

Reputation: 168

If your try block runs successfully then you are closing your connection twice. I think you can put it in finally block, that will solve your problem.

Upvotes: 2

dylrei
dylrei

Reputation: 1736

Indent the second conn.close(), otherwise you're closing a closed connection after a successful query.

Upvotes: 1

Related Questions