我正在尝试创建一个函数来初始化 MySQL + Python 连接。这是我目前所拥有的:
import mysql.connector
MySQLConfig = {
'user': 'user',
'password': 'password',
'host': 'localhost',
'database': 'DB',
'raise_on_warnings': True,
}
# Initialize MySQL Connection + Cursor
def createCursor():
cnx = mysql.connector.connect(**MySQLConfig)
cursor = cnx.cursor()
return cursor
cursor = createCursor()
query = 'SHOW tables'
cursor.execute(query)
for row in cursor:
print(row)
如果不包含在 createCursor()
函数中,代码将正常运行。一旦我把它放在一个我收到以下错误:
Traceback (most recent call last):
File "./config.py", line 24, in <module>
cursor.execute(query)
File "/Library/Python/2.7/site-packages/mysql/connector/cursor.py", line 473, in execute
if not self._connection:
ReferenceError: weakly-referenced object no longer exists
关于我可能需要做什么的任何想法?我试过仅返回连接并在函数外部使用游标,这也会导致同样的错误。
最佳答案
因为您已将 cnx 设为局部变量,所以它会在函数结束时被垃圾回收..
像这样做
cnx = mysql.connector.connect(**MySQLConfig)
# Initialize Cursor
def createCursor():
return cnx.cursor()
但这是个坏主意。我的方法是这样的
import mysql.connector
class MysqlHelper:
def __init__(self):
MySQLConfig = {'user': 'user','password': 'password','host': 'localhost','database': 'DB','raise_on_warnings': True}
self.cnx = mysql.connector.connect(**MySQLConfig)
self.cursor = self.cnx.cursor()
def execute_query(self,query):
self.cursor.execute(query)
for row in self.cursor:
print(row)
mysql_helper = MysqlHelper()
mysql_helper.execute_query("SHOW tables")
关于python - 使用 Python 创建 MySQL 游标函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29199834/