python mysqldb 多个连接

标签 python connection mysql-python

大家好, 我有以下问题: 1 个进程执行一个非常大的查询并将结果写入文件,在进程之间应将状态更新到数据库。

首先想到:没问题,伪代码:

db = mysqldb.connect()
cursor = db.cursor()
large = cursor.execute(SELECT * FROM VERYLARGETABLE)
for result in large.fetchall():
     file.write(result)
if timetoUpdateStatus: cursor.execute(UPDATE STATUS)

问题:当获得 900 万个结果时,“large = cursor.execute(SELECT * FROM VERYLARGETABLE)”永远不会完成...我在 4 列的 200 万个条目处找到了一个边界,其中 mysql 服务器在 30 之后完成了查询秒,但 python 进程持续运行数小时......这可能是 Python MySQLDB 库中的错误......

第二次尝试:使用 db.use_results() 和 fetch_row() 的 db.query 函数:

db = mysqldb.connect()
cursor = db.cursor()
db.query(SELECT * FROM VERYLARGETABLE)
large = large.use_result()
while true:
    for row in large.fetch_row(100000):
        file.write(row)
    if timetoUpdateStatus: cursor.execute(UPDATE STATUS) <-- ERROR (2014, "Commands out of sync; you can't run this command now")

所以第三次尝试使用了 2 个 MySQL 连接...这不起作用,当我打开第二个连接时,第一个连接消失了...

有什么建议吗??

最佳答案

尝试使用 MySQL SSCursor .它将结果集保留在服务器(MySQL 数据结构)中,而不是将结果集传输到客户端(Python 数据结构),这是默认游标所做的。使用 SSCursor 将避免由于默认游标试图构建 Python 数据结构并为其分配内存而导致的长时间初始延迟巨大的结果集。因此,SSCursor 也应该需要更少的内存。

import MySQLdb
import MySQLdb.cursors
import config

cons = [MySQLdb.connect(
    host=config.HOST, user=config.USER,
    passwd=config.PASS, db=config.MYDB,
    cursorclass=MySQLdb.cursors.SSCursor) for i in range(2)]
select_cur, update_cur = [con.cursor() for con in cons]
select_cur.execute(SELECT * FROM VERYLARGETABLE)
for i, row in enumerate(select_cur):
    print(row)
    if i % 100000 == 0 or timetoUpdateStatus:
        update_cur.execute(UPDATE STATUS)

关于python mysqldb 多个连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6035312/

相关文章:

python - pyspark - LinearRegression.load() 抛出 NoSuchMethodException

java - URLConnection.getInputStream() : Connection timed out

python - 使用 MySQLdb for Python 时如何使用选项 skip-name-resolve?

python - zip 列表太多项目无法解压

Linux + Apache检测每个Vhost的连接计数?

python :MYSQLdb。如何在不执行 select * 在大表中获取列名?

python - 我试图打印 1~50 范围内的偶数的这个函数有什么问题

python - 如何在python 2.7中保留通过yield生成的函数的方法属性?

python - 如何使用 Python 求解具有 16 个未知数的 4 x 4 数组(更新)

mysql - rails + database.yml 中的最大连接池大小