【发布时间】:2014-11-04 11:47:03
【问题描述】:
当生成大量结果集时,典型的 MySQLdb 库查询可能会使用大量内存并且在 Python 中表现不佳。例如:
cursor.execute("SELECT id, name FROM `table`")
for i in xrange(cursor.rowcount):
id, name = cursor.fetchone()
print id, name
有一个可选的游标一次只获取一行,确实加快了脚本的速度并大大减少了脚本的内存占用。
import MySQLdb
import MySQLdb.cursors
conn = MySQLdb.connect(user="user", passwd="password", db="dbname",
cursorclass = MySQLdb.cursors.SSCursor)
cur = conn.cursor()
cur.execute("SELECT id, name FROM users")
row = cur.fetchone()
while row is not None:
doSomething()
row = cur.fetchone()
cur.close()
conn.close()
但我找不到任何关于将SSCursor 与嵌套查询一起使用的信息。如果这是doSomething()的定义:
def doSomething()
cur2 = conn.cursor()
cur2.execute('select id,x,y from table2')
rows = cur2.fetchall()
for row in rows:
doSomethingElse(row)
cur2.close()
然后脚本抛出以下错误:
_mysql_exceptions.ProgrammingError: (2014, "Commands out of sync; you can't run this command now")
听起来好像SSCursor 与嵌套查询不兼容。真的吗?如果是这样,那就太糟糕了,因为使用标准光标时主循环似乎运行得太慢了。
【问题讨论】:
标签: python mysql-python