

These consequences can come as a surprise when sqlite3 has silently opened a transaction without your knowledge.

Turn on foreign key enforcementįoreign key constraints are not enforced by default in SQLite. It's worth reading that first, as this post covers different topics. The official documentation for Python's sqlite3 module already has a section on "Using sqlite3 efficiently".

I'd like to share a few lessons I have learned on using SQLite effectively in Python. It is lightweight, reliable, well-documented, and better than the filesystem for persistent storage. Otherwise leave it at its default, which will result in a plain “BEGIN” statement, or set it to one of SQLite’s supported isolation levels: “DEFERRED”, “IMMEDIATE” or “EXCLUSIVE”.I use SQLite as the database for my personal projects in Python. If you want autocommit mode, then set isolation_level to None. You can control which kind of BEGIN statements sqlite3 implicitly executes (or none at all) via the isolation_level parameter to the connect() call, or via the isolation_level property of connections. The other reason is that sqlite3 needs to keep track of the transaction state (if a transaction is active or not). The first is that some of these commands don’t work within transactions. , VACUUM, PRAGMA, the sqlite3 module will commit implicitly before executing that command. So if you are within a transaction and issue a command like CREATE TABLE. anything other than SELECT or the aforementioned). INSERT/ UPDATE/ DELETE/ REPLACE), and commits transactions implicitly before a non-DML, non-query statement (i. However, Python tries to be clever and automatically begins transactions:īy default, the sqlite3 module opens transactions implicitly before a Data Modification Language (DML) statement (i.e.
