Why won't Python return my mysql-connector cursor from a function?

扶醉桌前 提交于 2019-12-01 05:53:17

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.

Can you print type(connect) in your function?

Sample:

>>> import MySQLdb as mydb
>>> def runQuery(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))
>>>
>>>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!