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