3
我用下面的python3代碼在一個sqlite3的數據庫中添加和更新條目大量條目:進入一個SQLite數據庫
def increment_person_counts(count_per_person):
with sqlite3.connect(r'./people_database') as connection:
cursor = connection.cursor()
for person in count_per_person:
if cursor.execute('select * from personCounts where person = ?', [person]).fetchone()==None:
cursor.execute('insert into personCounts(person, count) values (?, ?)', [person, count_per_person[person]])
else:
cursor.execute('update personCounts SET count=count + ? WHERE person=?', [count_per_person[person], person])
connection.commit()
count_per_person中包含4萬個條目,我似乎能夠添加/每秒更新大約100個條目,這意味着需要半天才能添加這些值。有沒有更好/更快的方法來做到這一點,我應該考慮?
感謝您的幫助,
巴里
沒錯,好主意! – Baz 2011-12-22 09:07:14
@Baz - 你也可以在插入時試用'executemany'方法:http://docs.python.org/library/sqlite3.html#sqlite3.Cursor.executemany – eumiro 2011-12-22 09:09:20
是的,特別是在我插入新條目之後以及將現有條目更新爲單獨的python函數,分別建立了需要更新或添加的內容。 – Baz 2011-12-22 09:14:56