Store data in SQLite
sqlite.open takes a file permission, so a library cannot open databases
outside the folder it was given. Values always go into a statement as
? parameters, never pasted into the SQL text, so a value cannot change
what the statement does.
import fsimport sqlite
let mut db = try sqlite.open(&fs.files(), &":memory:")try db.exec(&"CREATE TABLE notes (id INTEGER PRIMARY KEY, title TEXT NOT NULL, stars INTEGER)")
let titles = ["Buy tea", "Robert'); DROP TABLE notes;--", "Write docs"]for i in 0..titles.len() { let _ = try db.run(&"INSERT INTO notes (title, stars) VALUES (?, ?)", &[sqlite.Value.Text(titles[i].clone()), sqlite.Value.Int(i + 3)])}print(f"last id {db.last_id()}")
let rows = try db.query(&"SELECT title, stars FROM notes WHERE stars >= ? ORDER BY stars DESC", &[sqlite.Value.Int(4)])for row in &rows { print(f"{row.int(&"stars").unwrap()} {row.text(&"title").unwrap()}")}
let bad = db.query(&"SELECT nope FROM notes", &[]) catch { sqlite.SqlError(e) => { print("error: " + e.message) [] }}print(f"{bad.len()} rows")last id 35 Write docs4 Robert'); DROP TABLE notes;--error: no such column: nope0 rowsTo keep the data, pass a file name such as &"notes.db" instead of
":memory:". The Db closes the file when it goes out of scope.