example/example_9.pyPython43 lines
example_9.py
Managed SQLite connection, transactions, bound parameters and health checks
example/example_9.py
Pythonimport sqlite3
from contextlib import closing
from pathlib import Path
from tempfile import TemporaryDirectory
import storq
def main() -> None:
with TemporaryDirectory() as directory:
database = Path(directory) / "managed.sqlite"
with closing(sqlite3.connect(database)) as connection:
connection.execute(
"CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT)"
)
with storq.open_database(database) as managed:
managed.execute(
"INSERT INTO items(name) VALUES (?)",
"first",
)
print("Inserted:", managed.fetchone(
"SELECT name FROM items WHERE id = 1"
))
with managed.transaction() as transaction:
transaction.execute(
"INSERT INTO items(name) VALUES (:name)",
{"name": "second"},
)
print("Transaction rows:", transaction.fetchall(
"SELECT name FROM items"
))
print("quick_check:", managed.quick_check())
print("integrity_check:", managed.integrity_check())
print("Managed connection open:", managed.is_open)
if __name__ == "__main__":
main()
