當生成大型結果集時,典型的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