Python为什么不从函数返回我的mysql-connector游标? [英] Why won't Python return my mysql-connector cursor from a function?

查看:104
本文介绍了Python为什么不从函数返回我的mysql-connector游标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我从函数返回它时,Python(2.7.3)以某种奇怪的方式违反了我的mysql-connector游标.第一个例子很好用...

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 MyTable"
cursor = cnx.cursor()
cursor.execute(sql)
row = cursor.fetchone()

但是,如果我返回游标并从外部尝试fetchone()(或fetchall()),则会引发异常...

However, if I return the cursor and attempt the fetchone() (or a fetchall()) from outside, it throws an exception...

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'

尽管事实上打印类型(mycursor)"将打印"mysql.connector.cursor.MySQLCursor"

This is in spite of the fact that "print type(mycursor)" will print "mysql.connector.cursor.MySQLCursor"

Python对从函数返回的对象执行哪种邪恶的骚扰? (请记住,它将对通过内部模块传递的游标执行此操作...因此,这与从"import mysql.connector"范围传递过来的对象不一样...)

What type of unholy molestation is Python performing on objects returned from functions? (Keep in mind that it will do this to cursors passed within a module... so, it's not like the object passed out of the "import mysql.connector" scope... )

推荐答案

我没有立即可用的MySQL,但是正如Preet Sangha所述,当您连接到函数内部的数据库并返回游标时,您的cnx变量该函数退出时超出范围,因此数据库连接关闭,并且光标引用了已关闭的数据库连接.

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.

这篇关于Python为什么不从函数返回我的mysql-connector游标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆