连接到 SQLite
在 Github 上编辑
使用 node:sqlite
模块,您可以连接到本地存储的 SQLite3 数据库并执行基本数据库操作。 node:sqlite
模块已在 Deno v2.2 中添加。
从 jsr:@db/sqlite 导入 Database 类
import { DatabaseSync } from "node:sqlite";
打开或创建名为 'test.db' 的 SQLite 数据库
const db = new DatabaseSync("test.db");
如果 "people" 表不存在,则创建该表
db.exec(
`
CREATE TABLE IF NOT EXISTS people (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
age INTEGER
);
`,
);
向 "people" 表中插入新行
db.prepare(
`
INSERT INTO people (name, age) VALUES (?, ?);
`,
).run("Bob", 40);
查询 "people" 表中的所有行
const rows = db.prepare("SELECT id, name, age FROM people").all();
console.log("People:");
for (const row of rows) {
console.log(row);
}
关闭数据库连接
db.close();
使用 Deno CLI 在本地运行此示例
deno run --allow-read --allow-write https://docs.deno.org.cn/examples/scripts/sqlite.ts