python - 使用 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 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/

相关文章:

php - 从 3 个 MySQL 表在 PHP 中构建一个冠军表

MySQL 到 PostgreSQL 转换和数据同步

python - scikit-learn 中的神经网络 epoch 和 max_iter

java - Python Azure 函数中的 Tika

mysql - 对两个表的 SQL 更新查询

mysql - 通过比较来自两个不同表的字符串来填充字段

java - 在mysql查询期间java代码中进行一些迭代后出现无限循环 "hangs"

python - 打印传递给函数的变量名称

python - 如何使用 Python Requests 模块登录 Google?

python - 如何使用 Celery 守护进程自动重新加载任务模块?