Library contents

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

  1. Start with Two rows containing 1 and 2
  2. Do this Sum the column
  3. Result 3
The aggregate turns the two rows into a single total.

Syntax

Python 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.

First output lineeast 7
lesson.py
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)
Output
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

Advertisements

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?

GivenRows 3 · 5 · 9
Worked result17

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?

GivenRows 8 · 2
Worked result10