Вы можете прочитать все свои 'select * from personCounts'
в питоне set()
в начале, а затем проверить только по этому набору.
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()
ОБНОВЛЕНИЕ : после моего комментария, вот обновление с executemany
:
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()