我的代码是:
import sqlite3
def connect():
conn = sqlite3.connect("books.db")
cur = conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS book (id INTEGER PRIMARY KEY, title text, author text, year integer)")
conn.commit()
conn.close()
def insert(title, author, year):
conn = sqlite3.connect("books.db")
cur = conn.cursor()
cur.execute("INSERT INTO book VALUES (NULL, ?, ?, ?)", (title, author, year))
conn.commit()
conn.close()
connect()
insert("Title", "Author", 1950)
我想使用WHERE NOT EXISTS SQL语句以避免重复输入。我尝试了在cur.execute()的WHERE NOT EXISTS中编写不同的方法,但一直得到:
sqlite3.OperationalError:邻近 “WHERE”:语法错误
答案 0 :(得分:1)
要避免重复插入,请使用唯一索引或约束:
create unique index unq_book_title_author_year on book(title, author, year);
这比not exists
更好,因为数据库强制执行唯一性。请注意,如果尝试重复插入,将尝试insert
然后失败。