Last active
April 26, 2024 13:04
-
-
Save shuson/11209728 to your computer and use it in GitHub Desktop.
weakly-referenced object when connect to mysql in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
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!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Worked for me.. thanks mate !