1import sqlite3 2 3con = sqlite3.connect(":memory:") 4con.execute("create table person (id integer primary key, firstname varchar unique)") 5 6# Successful, con.commit() is called automatically afterwards 7with con: 8 con.execute("insert into person(firstname) values (?)", ("Joe",)) 9 10# con.rollback() is called after the with block finishes with an exception, the 11# exception is still raised and must be caught 12try: 13 with con: 14 con.execute("insert into person(firstname) values (?)", ("Joe",)) 15except sqlite3.IntegrityError: 16 print("couldn't add Joe twice") 17 18# Connection object used as context manager only commits or rollbacks transactions, 19# so the connection object should be closed manually 20con.close() 21