-
-
Save shuson/11209728 to your computer and use it in GitHub Desktop.
I came across this issue using the following code file | |
the error message is ReferenceError: weakly-referenced object no longer exists | |
reason is in the mysql/connector/cursor.py file | |
see these lines: | |
def _set_connection(self, connection): | |
"""Set the connection""" | |
try: | |
self._connection = weakref.proxy(connection) | |
self._connection._protocol # pylint: disable=W0212,W0104 | |
except (AttributeError, TypeError): | |
raise errors.InterfaceError(errno=2048) | |
because the connection is weakref, so when we use its reference, it is unsafe. | |
To avoid this issue, use the test1 method. |
import mysql.connector as connector | |
def connection(): | |
config = { | |
"user": "root", | |
"password": "password", | |
"host": "localhost", | |
"port": 3306, | |
"database": "pydb" | |
} | |
try: | |
c = connector.connect(**config) | |
return c | |
except: | |
print "connection error" | |
exit(1) | |
def test(): # error method | |
cur= connection().cursor() | |
cur.execute("select version();") | |
print cur.fetchone() | |
def test1(): #no error method | |
cn = connection() | |
cur = cn.cursor() | |
cur.execute("select version;") | |
print cur.fetchone() |
it works! thanks!
I also got this error because of the connection going out of scope. connector.connect().cursor() has a reference to connector.connect(). If the latter goes out of scope, the cursor breaks:
def make_cursor:
conn = mysql.connector.connect(...)
return conn.cursor() # conn does not exist after this returns
def test3:
cursor = make_cursor()
cursor.execute(...) # does not work
The solution was to make a class to ensure conn does not get dropped:
class Conn:
def __init__(self):
self.conn = mysql.connector.connect(...)
self.cursor = self.conn.cursor()
def test4:
conn = Conn()
conn.cursor.execute(...) # works
Perfect !!! worked (y)
I also got this error because of the connection going out of scope. connector.connect().cursor() has a reference to connector.connect(). If the latter goes out of scope, the cursor breaks:
def make_cursor: conn = mysql.connector.connect(...) return conn.cursor() # conn does not exist after this returns def test3: cursor = make_cursor() cursor.execute(...) # does not work
The solution was to make a class to ensure conn does not get dropped:
class Conn: def __init__(self): self.conn = mysql.connector.connect(...) self.cursor = self.conn.cursor() def test4: conn = Conn() conn.cursor.execute(...) # works
Worked for me.. thanks mate !
perfect.. works spot on!!
please i don't know which code I have to use it
I have this error message can anyone help
weakly-referenced object no longer exists
thanks it work
@shehabhy1 test1 function solved that issue perfectly for me (reference connection and support in separate lines). Though I hope you solved the problem since then :D
Kudos @op for the clear and simple explaination!
perfect, it worked !!