用Python创建MySQL游标函数
我试图创建一个函数来初始化MySQL+Python连接。以下是我到目前为止的情况:用Python创建MySQL游标函数,python,mysql,Python,Mysql,我试图创建一个函数来初始化MySQL+Python连接。以下是我到目前为止的情况: import mysql.connector MySQLConfig = { 'user': 'user', 'password': 'password', 'host': 'localhost', 'database': 'DB', 'raise_on_warnings': True, } # Initialize MySQL Connection + Cursor def create
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
回溯(最近一次呼叫最后一次):
文件“/config.py”,第24行,在
cursor.execute(查询)
文件“/Library/Python/2.7/site packages/mysql/connector/cursor.py”,第473行,在execute中
如果不是自连接:
ReferenceError:弱引用对象不再存在
关于我可能需要做什么有什么想法吗?我已尝试仅返回连接并在函数外使用光标,这也会导致相同的错误。由于您已将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")
太棒了,谢谢,这正是我需要的!为什么这是个坏主意呢?每次创建mysql游标而不是将其创建为全局变量是不好的。。。