我正在尝试使用 Python 和 MySQLdb 接口实现以下目标:
- 读取具有几百万行的表的内容。
- 处理和修改每一行的输出。
- 将修改后的行放到另一个表中。
对我来说,迭代每一行,即时处理,然后动态地将每一行插入新表中似乎是明智的。
这有效:
import MySQLdb
import MySQLdb.cursors
conn=MySQLdb.connect(
host="somehost",user="someuser",
passwd="somepassword",db="somedb")
cursor1 = conn.cursor(MySQLdb.cursors.Cursor)
query1 = "SELECT * FROM table1"
cursor1.execute(query1)
cursor2 = conn.cursor(MySQLdb.cursors.Cursor)
for row in cursor1:
values = some_function(row)
query2 = "INSERT INTO table2 VALUES (%s, %s, %s)"
cursor2.execute(query2, values)
cursor2.close()
cursor1.close()
conn.commit()
conn.close()
但这很慢且消耗内存,因为它使用客户端游标进行SELECT
查询。如果我改为使用服务器端游标进行SELECT
查询:
cursor1 = conn.cursor(MySQLdb.cursors.SSCursor)
然后我得到一个 2014 错误:
Exception _mysql_exceptions.ProgrammingError: (2014, "Commands out of sync; you can't run this command now") in <bound method SSCursor.__del__ of <MySQLdb.cursors.SSCursor object at 0x925d6ec>> ignored
所以它似乎不喜欢在迭代服务器端游标时启动另一个游标。这似乎让我陷入了一个非常慢的客户端迭代器。
有什么建议么?