当生成大型结果集时,典型的MySQLdb库查询可以使用大量内存并且在Python中执行效果很差。例如:将python MySQLDB SScursor与嵌套查询结合使用
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
不与嵌套查询兼容。真的吗?如果这样太糟糕了,因为主循环似乎与标准光标运行速度太慢。
蟒蛇 - 如此正确,如此缓慢在同一时间! – shigeta 2014-09-12 11:33:54