Skip to content Skip to sidebar Skip to footer

Why Won't Python Return My Mysql-connector Cursor From A Function?

Python (2.7.3) is violating my mysql-connector cursor in some strange way when I return it from a function. This first example works fine... cnx = connect() sql = 'SELECT * FROM My

Solution 1:

I do not have MySQL immediately available, but as Preet Sangha mentioned, when you connect to the database inside the function and return the cursor, your cnx variable goes out of scope when the function exits, so the database connection closes and your cursor references a closed database connection.

This is not the case in your top code example, which may explain why it works and why the bottom example does not.

Solution 2:

Can you print type(connect) in your function?

Sample:

>>>import MySQLdb as mydb>>>defrunQuery(sql):...    db = mydb.connect('localhost', 'testuser', 'test', 'test')...    cur = db.cursor()...    cur.execute(sql)...    data = cur.fetchall()...print"Query :: %s"  %sql...print"Result:: %s" %data...return cur...>>>>>>cursor = runQuery("SELECT VERSION()")
Query :: SELECT VERSION()
Result:: ('5.6.11-log',)
>>>>>>cursor.execute("SELECT * FROM EMPLOYEES")
3L
>>>data = cursor.fetchall()>>>>>>print data
(('JOHN', 30L, 23000.0), ('SONY', 26L, 14000.0), ('SMITH', 53L, 123000.0))
>>>>>>

Post a Comment for "Why Won't Python Return My Mysql-connector Cursor From A Function?"