python - WHERE NOT EXISTS SQL statement in sqlite3 -
this question has answer here:
my code this:
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 book values (null, ?, ?, ?)", (title, author, year)) conn.commit() conn.close() connect() insert("title", "author", 1950)
i use not exists sql statement in order avoid duplicate inputs. tried different ways of writing in not exists along cur.execute() keep getting:
sqlite3.operationalerror: near "where": syntax error
to avoid duplicate inserts, use unique index or constraint:
create unique index unq_book_title_author_year on book(title, author, year);
this better not exists
because database enforces uniqueness. note insert
attempted , fail, if duplicate insertions attempted.
Comments
Post a Comment