''' Example from https://docs.python.org/2.7/library/sqlite3.html with minor revisions. 2018-03-08 ''' import sqlite3 con = sqlite3.connect(":memory:") con.execute("create table person (id integer primary key, firstname varchar unique)") # Successful, con.commit() is called automatically afterwards with con: con.execute("insert into person(firstname) values (?)", ("Joe",)) con.execute("insert into person(firstname) values (?)", ("Zack",)) cursor = con.execute("select * from person;") for row in cursor: print("first name : ", row[1]) # con.rollback() is called after the with block finishes with an exception, the # exception is still raised and must be caught try: with con: con.execute("insert into person(firstname) values (?)", ("Joe",)) con.commit() except sqlite3.IntegrityError: con.rollback() print("couldn't add Joe twice") cursor = con.execute("select * from person;") for row in cursor: print("first name : ", row[1])