![](/img/trans.png)
[英]What is the proper way of using MySQLdb connections and cursors across multiple functions in Python
[英]python mysqldb multiple connections
嘿伙計們,我有以下問題: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)”永遠不會完成...我想出了一個邊界,在2列位置,在4列,其中mysql服務器在30秒后完成查詢但是python進程持續運行數小時...這可能是Python MySQLDB庫中的一個錯誤..
SO SECOND TRY:db.query函數與db.use_results()和fetch_row():
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)
嘗試將“select * from db”查詢拆分為較小的塊
index=0
while True:
cursor.execute('select * from verylargetable LIMIT %s,%s', (index, index+10000))
records = cursor.fetchall()
if len(records)==0:
break
file.write(records)
index+=10000
file.close()
在LIMIT
中使用LIMIT
語句:
limit = 0
step = 10000
query = "SELECT * FROM VERYLARGETABLE LIMIT %d, %d"
db = mysqldb.connect()
cursor = db.cursor()
while true:
cursor.execute(query, (step, limit))
for row in cursor.fetch_all():
file.write(row)
if timetoUpdateStatus:
cursor.execute(update_query)
limit += step
代碼未經過測試,但您應該明白這一點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.