[英]How do I speed up my sqlite3 queries in Python?
我有一個包含幾億行的sqlite表:
sqlite> create table t1(id INTEGER PRIMARY KEY,stuff TEXT );
我需要通過其整數主鍵查詢該表數億次。 我的代碼:
conn = sqlite3.connect('stuff.db')
with conn:
cur = conn.cursor()
for id in ids:
try:
cur.execute("select stuff from t1 where rowid=?",[id])
stuff_tuple = cur.fetchone()
#do something with the fetched row
except:
pass #for when id is not in t1's key set
在此,id是一個可能包含成千上萬個元素的列表。 形成t1並不需要很長時間(即每秒插入約75K)。 用我做過的方式查詢t1的速度實在令人難以接受(即10秒鍾內約有1K次查詢)。
我對SQL完全陌生。 我究竟做錯了什么?
您應該改用一個sql調用,應該更快
conn = sqlite3.connect('stuff.db')
with conn:
cur = conn.cursor()
for row in cur.execute("SELECT stuff FROM t1 WHERE rowid IN (%s)" % ','.join('?'*len(ids)), ids):
#do something with the fetched row
pass
您不需要嘗試,因為不會顯示數據庫中沒有的ID。 如果您想知道結果中沒有哪些ID,可以執行以下操作:
ids_res = set()
for row in c.execute(...):
ids_res.add(row['id'])
ids_not_found = ids_res.symmetric_difference(ids)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.