Complete worked example
python
from sqlalchemy import create_engine, text
def inspect_example(scores, minimum):
engine = create_engine("sqlite+pysqlite://", connect_args={"autocommit": False})
try:
with engine.begin() as connection:
connection.execute(text("CREATE TABLE roles (score INTEGER NOT NULL)"))
if scores:
connection.execute(text("INSERT INTO roles VALUES (:score)"),
[{"score": value} for value in scores])
with engine.connect() as connection:
statement = text("SELECT score FROM roles WHERE score >= :minimum ORDER BY score")
return list(connection.scalars(statement, {"minimum": minimum}))
finally:
engine.dispose()- Reasoning
- The complete example creates a tiny roles table, inserts the supplied scores inside engine.begin(), and reads through another connection. Successful exit from begin commits that block; an exception rolls it back. Opening a connection with engine.connect() does not mean that successful exit commits pending writes. The minimum travels in a parameter dictionary. The SQL text contains :minimum rather than a formatted number or a quoted user string. For scores [4, 2, 4, 1] and minimum 2, the independently expected ordered result is [2, 4, 4]. Duplicate observations remain duplicate rows.