39 lines
1.4 KiB
Lua
39 lines
1.4 KiB
Lua
-- Showcase the calog db library on SQLite: open an in-memory database, create a
|
|
-- table, insert several rows using BOUND parameters (safe from injection), run a
|
|
-- SELECT and print each returned row map field by field, run a COUNT aggregate,
|
|
-- then close the handle.
|
|
-- Run: bin/calog examples/scripts/libraries/database.lua
|
|
|
|
local db = dbOpen("sqlite", ":memory:")
|
|
|
|
dbExec(db, "CREATE TABLE fruit (id INTEGER PRIMARY KEY, name TEXT, qty INTEGER, price REAL)")
|
|
|
|
-- Insert rows with bound parameters. dbExec returns rows affected.
|
|
local stock = {
|
|
{ "apple", 12, 0.35 },
|
|
{ "banana", 30, 0.20 },
|
|
{ "cherry", 8, 1.10 },
|
|
{ "date", 15, 0.75 },
|
|
}
|
|
|
|
local inserted = 0
|
|
for _, item in ipairs(stock) do
|
|
inserted = inserted + dbExec(db, "INSERT INTO fruit (name, qty, price) VALUES (?, ?, ?)", item[1], item[2], item[3])
|
|
end
|
|
calogPrint("rows inserted:", inserted)
|
|
|
|
-- SELECT returning a list of row maps. Print each field explicitly.
|
|
local rows = dbQuery(db, "SELECT id, name, qty, price FROM fruit WHERE qty >= ? ORDER BY name", 10)
|
|
calogPrint("rows with qty >= 10:", #rows)
|
|
for _, row in ipairs(rows) do
|
|
calogPrint(string.format(" #%d %-7s qty=%d price=%.2f", row.id, row.name, row.qty, row.price))
|
|
end
|
|
|
|
-- Aggregate query: COUNT and SUM in a single row.
|
|
local summary = dbQuery(db, "SELECT COUNT(*) AS n, SUM(qty) AS total FROM fruit")
|
|
calogPrint("distinct fruits:", summary[1].n)
|
|
calogPrint("total quantity:", summary[1].total)
|
|
|
|
dbClose(db)
|
|
|
|
calogExit(0)
|