Open this example in the interactive library
Source code
from contextlib import closing
import sqlite3
with closing(sqlite3.connect(':memory:')) as db:
db.execute('CREATE TABLE tasks (id INTEGER PRIMARY KEY)')
try:
with db:
db.executemany('INSERT INTO tasks VALUES (?)', [(1,), (1,)])
except sqlite3.IntegrityError:
print(db.execute('SELECT COUNT(*) FROM tasks').fetchone()[0])Sample output
0
