我想向数据库中插入新的问题信息。我是sqlite3的新手,对于任何错误,我们深表歉意。我正在使用sqlite3和python3。 我正在尝试插入新的行,该行对应于Competition_id和problem_id定义的每个问题(common_id和problem_id的每对都引用一个唯一的问题)。但是,如果相应的行已经存在,我将保持原样。 这是表模式:
CREATE TABLE problems (
contest_id INT NOT NULL,
contest_name TEXT,
problem_id CHAR(10) NOT NULL,
problem_name TEXT,
CONSTRAINT Problem_info PRIMARY KEY(contest_id, problem_id) )
Python脚本:
import sqlite3
import sys
conn = sqlite3.connect('sqlite.db')
cur = conn.cursor()
contest_id = (sys.argv)[1]
problem_list_1 = (sys.argv)[2:]
problem_list_2 = list(cur.execute('SELECT problem_id FROM problems WHERE contest_id = '+str(contest_id)).fetchall())
conn.commit()
problem_list = list(set(problem_list_1) - set(problem_list_2))
problem_list.sort()
for problem in problem_list:
cur.execute('INSERT INTO problems (contest_id, contest_name, problem_id, problem_name) VALUES('+str(contest_id)+', "dummy_name"'+', "'+problem+'", "dummy_name")')
conn.commit()
print(conn.execute('SELECT * FROM problems').fetchall())
conn.commit()
conn.close()
这是我输入的序列中的参数和输出对:
1159 A B C
[(1159, 'dummy_name', 'A', 'dummy_name'), (1159, 'dummy_name', 'B', 'dummy_name'), (1159, 'dummy_name', 'C', 'dummy_name')]
1167 A
[(1159, 'dummy_name', 'A', 'dummy_name'), (1159, 'dummy_name', 'B', 'dummy_name'), (1159, 'dummy_name', 'C', 'dummy_name'), (1167, 'dummy_name', 'A', 'dummy_name')]
1159 D
[(1159, 'dummy_name', 'A', 'dummy_name'), (1159, 'dummy_name', 'B', 'dummy_name'), (1159, 'dummy_name', 'C', 'dummy_name'), (1167, 'dummy_name', 'A', 'dummy_name'), (1159, 'dummy_name', 'D', 'dummy_name')]
1159 A B E
Traceback (most recent call last):
File "update_contest.py", line 15, in <module>
cur.execute('INSERT INTO problems (contest_id, contest_name, problem_id, problem_name) VALUES('+str(contest_id)+', "dummy_name"'+', "'+problem+'", "dummy_name")')
sqlite3.IntegrityError: UNIQUE constraint failed: problems.contest_id, problems.problem_id
在重复问题时,由于出现此错误,看来issue_list_2仍然为空。