2011-12-22 4 views
3

私はsqlite3のデータベースにエントリを追加して更新するには、以下ののpython3コードを使用:/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 400万件のエントリが含まれていて、私が追加できるように思われます1秒間に約100件のエントリが更新されます。つまり、これらの値を追加するのに半日かかります。私が検討すべきこれを行うためのより良い/より速いアプローチがありますか?あなたの助けのための

おかげで、

バリー

答えて

2

あなたは冒頭でpythonのset()にあなたの全体'select * from personCounts'を読み、そしてちょうどこのセットに対して確認することができます。

def increment_person_counts(count_per_person): 
    with sqlite3.connect(r'./people_database') as connection: 
     cursor = connection.cursor() 
     cursor.execute('select person from personCounts') 
     known_persons = set(row[0] for row in cursor.fetchall()) 
     for person, count in count_per_person.iteritems(): 
     if person in known_persons: 
      cursor.execute('insert into personCounts(person, count) values (?, ?)', [person, count]) 
     else: 
      cursor.execute('update personCounts SET count=count + ? WHERE person=?', [count, person]) 
     connection.commit() 

UPDATE

def increment_person_counts(count_per_person): 
    with sqlite3.connect(r'./people_database') as connection: 
     cursor = connection.cursor() 
     cursor.execute('select person from personCounts') 
     known_persons = set(row[0] for row in cursor.fetchall()) 
     cursor.executemany('insert into personCounts(person, count) values (?, ?)', ((person, count) for count_per_person.iteritems() if person in known_persons)) 
     for person, count in count_per_person.iteritems(): 
      if person not in known_persons: 
       cursor.execute('update personCounts SET count=count + ? WHERE person=?', [count, person]) 
     connection.commit() 
+0

はい、良いアイデア:私のコメントの後、ここにexecutemanyと更新です! – Baz

+0

@Baz - 挿入するときに 'executemany'メソッドを試すこともできます:http://docs.python.org/library/sqlite3.html#sqlite3.Cursor.executemany – eumiro

+0

はい、特に新しいエントリの挿入を分割した後既存のエントリを個別のPython関数に更新し、更新または追加する必要があるものを個別に確立しました。 – Baz

関連する問題