cnx = connect()
sql = "SELECT * FROM MyTable"
cursor = cnx.cursor()
cursor.execute(sql)
row = cursor.fetchone()
但是,如果我返回光标并从外部尝试fetchone()(或fetchall()),则会抛出异常......
def run_query():
cnx = connect()
sql = "SELECT * FROM MyTable"
cursor = cnx.cursor()
cursor.execute(sql)
return cursor
mycursor = run_query()
row = mycursor.fetchone()
它抛出......
File "/usr/lib/pymodules/python2.7/mysql/connector/cursor.py", line 533, in fetchone
row = self._fetch_row()
File "/usr/lib/pymodules/python2.7/mysql/connector/cursor.py", line 508, in _fetch_row
(row, eof) = self.db().protocol.get_row()
AttributeError: 'NoneType' object has no attribute 'protocol'
尽管“print type(mycursor)”将打印“mysql.connector.cursor.MySQLCursor”
Python对函数返回的对象执行什么类型的邪恶骚扰? (请记住,对于在模块中传递的游标,它会执行此操作...因此,它不像从“import mysql.connector”范围传出的对象...)
答案 0 :(得分:4)
我没有立即可用的MySQL,但正如Preet Sangha所提到的,当你连接到函数内部的数据库并返回光标时,当函数退出时,你的cnx
变量超出了范围,所以数据库连接关闭,光标引用已关闭的数据库连接。
在您的顶级代码示例中并非如此,这可能解释了它的工作原理以及为什么底部示例没有。
答案 1 :(得分:0)
您可以在功能中打印类型(连接)吗?
样品:
>>> 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))
>>>
>>>