Python sqlite3.executemany and execute
sqlite3 opens a local SQL database. executemany binds a batch of parameter tuples, while execute returns a cursor for a single query.
A simple example
sqlite3.executemany and execute
- Start with Two rows containing 1 and 2
- Do this Sum the column
- Result 3
Syntax
connection.executemany("INSERT INTO readings VALUES (?, ?)", rows)
Run this example in Python
Save the program as lesson.py. Use Python 3.9 or later.
python3 lesson.py
Aggregate readings in an in-memory database
A team receives a batch of readings or transactions and wants a compact report. Aggregate the records by the requested grouping so the result can be checked against the individual inputs.
from contextlib import closing
import sqlite3
with closing(sqlite3.connect(":memory:")) as db:
with db:
db.execute("CREATE TABLE readings (region TEXT, qty INTEGER)")
db.executemany("INSERT INTO readings VALUES (?, ?)",
[("east", 3), ("west", 1), ("east", 4)])
query = "SELECT region, SUM(qty) FROM readings GROUP BY region ORDER BY region"
for region, total in db.execute(query):
print(region, total)
east 7 west 1
Place values in parameters to preserve their types and treat them as data. The connection context manager commits or rolls back a transaction. closing also closes the connection afterward.
Python documentation for sqlite3.executemany and execute
Total art-room orders
A school enters one quantity per stationery order. Store the batch counts in separate rows and ask the database for their sum. Which total should appear?
Total returns at two desks
Two library desks log the number of returned kits. Store the batch counts in separate rows and ask the database for their sum. Which total should appear?