Use the UNIQUE
keyword when creating the table and use INSERT OR INGORE
to insert only if the record is "new" (unique):
connection=sqlite3.connect(':memory:') cursor=connection.cursor() cursor.execute('CREATE TABLE foo (bar INTEGER UNIQUE, baz INTEGER)')
Here we insert the line once:
cursor.execute('INSERT INTO foo (bar,baz) VALUES (?, ?)',(1,2))
Re-attempting to re-install the line fails:
try: cursor.execute('INSERT INTO foo (bar,baz) VALUES (?, ?)',(1,2)) except sqlite3.IntegrityError as err: print(err)
INSERT OR IGNORE
inserts a record only if a UNIQUE
constraint is passed:
cursor.execute('INSERT OR IGNORE INTO foo (bar,baz) VALUES (?, ?)',(1,3)) cursor.execute('SELECT * from foo') data=cursor.fetchall() print(data) # [(1, 2)]
To create a UNIQUE
index for multiple fields, use something like
cursor.execute(''' CREATE TABLE foo (bar INTEGER, baz INTEGER, bing INTEGER, UNIQUE (bar, baz))''')
Here are links to information on