Gerhard Häring | 0d7d6cf | 2008-03-29 01:32:44 +0000 | [diff] [blame] | 1 | import sqlite3 |
| 2 | |
| 3 | con = sqlite3.connect(":memory:") |
| 4 | con.execute("create table person (id integer primary key, firstname varchar unique)") |
| 5 | |
| 6 | # Successful, con.commit() is called automatically afterwards |
| 7 | with 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 |
Sandro Tosi | 567493f | 2011-10-31 02:41:06 +0100 | [diff] [blame] | 11 | # exception is still raised and must be caught |
Gerhard Häring | 0d7d6cf | 2008-03-29 01:32:44 +0000 | [diff] [blame] | 12 | try: |
| 13 | with con: |
| 14 | con.execute("insert into person(firstname) values (?)", ("Joe",)) |
| 15 | except sqlite3.IntegrityError: |
| 16 | print("couldn't add Joe twice") |