Transactions with Python sqlite3

后端 未结 7 1652
梦如初夏
梦如初夏 2020-12-07 17:33

I\'m trying to port some code to Python that uses sqlite databases, and I\'m trying to get transactions to work, and I\'m getting really confused. I\'m really confused by th

7条回答
  •  既然无缘
    2020-12-07 18:25

    Per the docs,

    Connection objects can be used as context managers that automatically commit or rollback transactions. In the event of an exception, the transaction is rolled back; otherwise, the transaction is committed:

    Therefore, if you let Python exit the with-statement when an exception occurs, the transaction will be rolled back.

    import sqlite3
    
    filename = '/tmp/test.db'
    with sqlite3.connect(filename) as conn:
        cursor = conn.cursor()
        sqls = [
            'DROP TABLE IF EXISTS test',
            'CREATE TABLE test (i integer)',
            'INSERT INTO "test" VALUES(99)',]
        for sql in sqls:
            cursor.execute(sql)
    try:
        with sqlite3.connect(filename) as conn:
            cursor = conn.cursor()
            sqls = [
                'update test set i = 1',
                'fnord',   # <-- trigger error
                'update test set i = 0',]
            for sql in sqls:
                cursor.execute(sql)
    except sqlite3.OperationalError as err:
        print(err)
        # near "fnord": syntax error
    with sqlite3.connect(filename) as conn:
        cursor = conn.cursor()
        cursor.execute('SELECT * FROM test')
        for row in cursor:
            print(row)
            # (99,)
    

    yields

    (99,)
    

    as expected.

提交回复
热议问题