1 | n/a | import sqlite3 |
---|
2 | n/a | |
---|
3 | n/a | con = sqlite3.connect(":memory:") |
---|
4 | n/a | con.execute("create table person (id integer primary key, firstname varchar unique)") |
---|
5 | n/a | |
---|
6 | n/a | # Successful, con.commit() is called automatically afterwards |
---|
7 | n/a | with con: |
---|
8 | n/a | con.execute("insert into person(firstname) values (?)", ("Joe",)) |
---|
9 | n/a | |
---|
10 | n/a | # con.rollback() is called after the with block finishes with an exception, the |
---|
11 | n/a | # exception is still raised and must be caught |
---|
12 | n/a | try: |
---|
13 | n/a | with con: |
---|
14 | n/a | con.execute("insert into person(firstname) values (?)", ("Joe",)) |
---|
15 | n/a | except sqlite3.IntegrityError: |
---|
16 | n/a | print("couldn't add Joe twice") |
---|