Dev HelpersOpen library
← Back

Roll back a failed SQLite transaction

Roll back a failed SQLite transaction in Python.

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