1

How do I use sqlite transactions in python?

The following code raises the exception OperationalError: cannot commit - no transaction is active on the cur.execute('COMMIT') line:

import sqlite3
con = sqlite3.connect(':memory:')
cur = con.cursor()
cur.execute('CREATE TABLE test(p)')
cur.execute('BEGIN')
cur.execute('INSERT INTO test(p) values (?)', (1,))
cur.execute('COMMIT')

I've played around with isolation_level but none of the values gets rid of the exception.

simonzack
  • 19,729
  • 13
  • 73
  • 118

1 Answers1

1

Try turning on autocommit mode:

con.isolation_level = None

References:

Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • Tried all the other values forgot to try out `None` :( – simonzack Sep 05 '14 at 20:24
  • Doesn't autocommit mode mean that each `execute` is wrapped in a transaction? – simonzack Sep 05 '14 at 20:25
  • No. It means that each execute is wrapped in a transaction, **unless** there is a transaction pending. "*Autocommit mode is disabled by a BEGIN statement. Autocommit mode is re-enabled by a COMMIT or ROLLBACK.*" -- http://www.sqlite.org/c3ref/get_autocommit.html – Robᵩ Sep 05 '14 at 20:27