使用 ezsqlite 进行 SQLite 创建、插入和选择
任务
数据库 / SQLite / SQLite 创建、插入和选择
使用的 Opam 包
- ezsqlite 测试版本:0.4.2 — 使用的库:ezsqlite
代码
打开或创建(如果不存在)SQLite 数据库
let db = Ezsqlite.load "employees.sqlite"
创建 employees
表格。函数 run_ign
(“运行并忽略”)执行查询并丢弃数据库响应。
let () =
Ezsqlite.run_ign db
"CREATE TABLE employees (
name VARCHAR NOT NULL,
firstname VARCHAR NOT NULL,
age INTEGER NOT NULL
)"
()
type employee =
{ name:string; firstname:string; age:int }
let employees = [
{name = "Dupont"; firstname = "Jacques"; age = 36};
{name = "Legendre"; firstname = "Patrick"; age = 42}
]
let () =
函数 Ezsqlite.prepare
准备语句,以便稍后将实际值绑定到变量 :name
、:firstname
和 :age
。
let stmt = Ezsqlite.prepare db
{|
INSERT into employees
VALUES (:name, :firstname, :age)
|}
in
按顺序运行这些 Ezsqlite
函数会绑定来自 employee
记录的值并执行查询。
let insert_employee (employee: employee) =
Ezsqlite.clear stmt;
Ezsqlite.bind_dict stmt
[":name", Ezsqlite.Value.Text employee.name;
":firstname", Ezsqlite.Value.Text
employee.firstname;
":age", Ezsqlite.Value.Integer
(Int64.of_int employee.age)];
Ezsqlite.exec stmt
in
employees
|> List.iter insert_employee
iter
函数执行查询,然后将给定函数映射到数据库返回的所有行。
let () =
let stmt = Ezsqlite.prepare db
"SELECT name, firstname, age from employees"
in
let print_employee row =
Ezsqlite.text
、blob
、int64
、int
、double
函数可用于读取各个列的值。
请注意,这不是类型安全的,因为您需要在此处为列提供正确的类型。
let name = Ezsqlite.text row 0
and firstname = Ezsqlite.text row 1
and age = Ezsqlite.int row 2
in
Printf.printf "name=%s, firstname=%s, age=%d\n"
name firstname age
in
Ezsqlite.iter stmt print_employee