Open and Close SQLite Connections
Core idea
SQLite stores relational data without a separate database server. sqlite3.connect opens a database connection; the special name :memory: creates a private database that disappears when the connection closes. Execute SQL statements through the connection or a cursor. In these Python 3.12+ examples autocommit=False selects explicit transaction control; commit saves pending changes. closing closes the connection at the end of the block.
import sqlite3from contextlib import closingwith closing(sqlite3.connect(":memory:", autocommit=False)) as db: db.execute('CREATE TABLE bins (code TEXT, qty INTEGER)') db.execute('INSERT INTO bins VALUES (?, ?)', ('A', 6)) db.commit() print(db.execute('SELECT qty FROM bins').fetchone()[0])CREATE TABLE defines the columns; INSERT writes a row, SELECT reads it.
Check private database isolation
import sqlite3from contextlib import closingwith closing(sqlite3.connect(':memory:', autocommit=False)) as left, closing(sqlite3.connect(':memory:', autocommit=False)) as right: left.execute('CREATE TABLE bins (qty INTEGER)') left.commit() print(right.execute("SELECT count(*) FROM sqlite_master WHERE name='bins'").fetchone()[0])The second connection has its own database, not the table from the first.
Common mistake
A connection context manager manages transactions, not connection lifetime. Use closing or explicit close. A disk database needs a deliberate path and access policy; :memory: is not persistent.
Practice
Create an in-memory table for item names, insert two rows and select count(*). Close it and open another connection to verify isolation.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
SQLite connections
Check your understanding of sqlite connections.
What is printed?
import sqlite3from contextlib import closingwith closing(sqlite3.connect(":memory:", autocommit=False)) as db: print(db.execute('SELECT 2 + 5').fetchone()[0])What is printed?
import sqlite3from contextlib import closingwith closing(sqlite3.connect(":memory:", autocommit=False)) as db: db.execute('CREATE TABLE sample (n INTEGER)') print(db.execute('SELECT count(*) FROM sample').fetchone()[0])What happens to an ordinary :memory: database on close?
What closes the connection in these examples?