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()
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()
It throws...
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'
This is in spite of the fact that "print type(mycursor)" will print "mysql.connector.cursor.MySQLCursor"
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... )
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With