как продолжить цикл добавление пользователей в базу данных sqlite после исключения python
пожалуйста помогите разобраться почему
код перестает работает если появляется ошибка UNIQUE constraint failed:
при добавления не уникального ид
мне нужно добавить в базу данных списки с данными пользователей, в которых возможно что ид пользователей уже существует. их нужно пропустить. и добавить только уникальных пользователей. сейчас код перестает работать если пользователь не уникален.
import sqlite3
id = [12441, 21255021,]
name1 = ['name1', 'name2']
age1 = [ 23, 34]
city = ['city1', 'city2']
time = ['27.11.2022 4:15', '27.11.2022 4:15']
def insert_db(id, name1, age1, city, time):
connection = sqlite3.connect('new_db.sqlite')
cursor = connection.cursor()
cursor.execute("""
INSERT INTO test1 (id, name, age, city, joining_date,)
VALUES (?, ?, ?, ?, ?)
""", (id, name1, age1, city, time))
connection.commit()
for i in range(len(id)):
try:
insert_db(id[i], name1[i], age1[i], city[i], time[i])
print('уникальный')
except:
print('не уникальный')
Ответы (1 шт):
Автор решения: Namerek
→ Ссылка
import sqlite3
id = [12441, 21255021, ]
name1 = ['name1', 'name2']
age1 = [23, 34]
city = ['city1', 'city2']
time = ['27.11.2022 4:15', '27.11.2022 4:15']
def insert_db(id, name1, age1, city, time):
connection = sqlite3.connect('new_db.sqlite')
connection.execute(
"""
create table if not exists test1
(
id integer primary key,
name text,
age integer,
city text,
joining_date text
);
"""
)
cursor = connection.cursor()
cursor.execute("""
INSERT INTO test1 (id, name, age, city, joining_date)
VALUES (?, ?, ?, ?, ?) on conflict do nothing returning id
""", (id, name1, age1, city, time))
inserted_id, = cursor.fetchone() or (None,)
connection.commit()
return inserted_id
for i in range(len(id)):
if insert_db(id[i], name1[i], age1[i], city[i], time[i]):
print('уникальный')
else:
print('не уникальный')
Нужно чтобы id был уникальным индексом, к примеру primary key