sqlite中文文档|sqlite js中文教程|解析
用于 Node.js 应用程序的 SQLite 客户端
一个用 Typescript 编写的具有零依赖项的包装库,它将 ES6 承诺和基于 SQL 的迁移 API 添加到sqlite3 ( docs )。
注意v4 的sqlite
与 v3 相比有重大变化!请参阅CHANGELOG.md
了解更多详情。
安装
sqlite3
安装 大多数使用这个库的人都会使用sqlite3
作为数据库驱动程序。
任何符合sqlite3
( API ) 的库也应该可以工作。
$ npm install sqlite3 --save
sqlite
安装 # v4 of sqlite is targeted for nodejs 10 and on.
$ npm install sqlite --save
# If you need a legacy version for an older version of nodejs
# install v3 instead, and look at the v3 branch readme for usage details
$ npm install sqlite@3 --save
用法
该模块与原始sqlite3
库 ( docs )具有相同的 API ,除了它的所有 API 方法都返回 ES6 Promises 并且不接受回调参数(除了each()
)。
打开数据库
无缓存
import sqlite3 from 'sqlite3'
import { open } from 'sqlite'
// this is a top-level await
(async () => {
// open the database
const db = await open({
filename: '/tmp/database.db',
driver: sqlite3.Database
})
})()
或者
import sqlite3 from 'sqlite3'
import { open } from 'sqlite'
open({
filename: '/tmp/database.db',
driver: sqlite3.Database
}).then((db) => {
// do your thing
})
或者
import sqlite3 from 'sqlite3'
import { open } from 'sqlite'
// you would have to import / invoke this in another file
export async function openDb () {
return open({
filename: '/tmp/database.db',
driver: sqlite3.Database
})
}
带缓存
如果要启用数据库对象缓存
import sqlite3 from 'sqlite3'
import { open } from 'sqlite'
(async () => {
const db = await open({
filename: '/tmp/database.db',
driver: sqlite3.cached.Database
})
})()
启用详细/调试模式
import sqlite3 from 'sqlite3'
sqlite3.verbose()
跟踪 SQL 错误
有关更多信息,请参阅此文档。
db.on('trace', (data) => {
})
使用自定义驱动程序
您可以使用替代库,sqlite3
只要它符合sqlite3
API。
例如,使用sqlite3-offline
:
import sqlite3Offline from 'sqlite3-offline'
import { open } from 'sqlite'
(async () => {
const db = await open({
filename: '/tmp/database.db',
driver: sqlite3Offline.Database
})
})()
打开多个数据库
import sqlite3 from 'sqlite3'
import { open } from 'sqlite'
(async () => {
const [db1, db2] = await Promise.all([
open({
filename: '/tmp/database.db',
driver: sqlite3.Database
}),
open({
filename: '/tmp/database2.db',
driver: sqlite3.Database
}),
])
await db1.migrate({
migrationsPath: '...'
})
await db2.migrate({
migrationsPath: '...'
})
})()
open
配置参数
// db is an instance of `sqlite#Database`
// which is a wrapper around `sqlite3#Database`
const db = await open({
/**
* Valid values are filenames, ":memory:" for an anonymous in-memory
* database and an empty string for an anonymous disk-based database.
* Anonymous databases are not persisted and when closing the database
* handle, their contents are lost.
*/
filename: string
/**
* One or more of sqlite3.OPEN_READONLY, sqlite3.OPEN_READWRITE and
* sqlite3.OPEN_CREATE. The default value is OPEN_READWRITE | OPEN_CREATE.
*/
mode?: number
/**
* The database driver. Most will install `sqlite3` and use the `Database` class from it.
* As long as the library you are using conforms to the `sqlite3` API, you can use it as
* the driver.
*
* @example
*
* ```
* import sqlite from 'sqlite3'
*
* const driver = sqlite.Database
* ```
*/
driver: any
})
例子
src/**/__tests__
更多示例用法见目录- 有关
docs/
完整文档,请参阅目录。 - 另请访问
sqlite3
库API 文档
创建表并插入数据
await db.exec('CREATE TABLE tbl (col TEXT)')
await db.exec('INSERT INTO tbl VALUES ("test")')
获取单行
const result = await db.get('SELECT col FROM tbl WHERE col = ?', 'test')
// { col: 'test' }
const result = await db.get('SELECT col FROM tbl WHERE col = ?', ['test'])
// { col: 'test' }
const result = await db.get('SELECT col FROM tbl WHERE col = :test', {
':test': 'test'
})
// { col: 'test' }
获取多行
const result = await db.all('SELECT col FROM tbl')
// [{ col: 'test' }]
插入行
const result = await db.run(
'INSERT INTO tbl (col) VALUES (?)',
'foo'
)
/*
{
// row ID of the inserted row
lastID: 1,
// instance of `sqlite#Statement`
// which is a wrapper around `sqlite3#Statement`
stmt: <Statement>
}
*/
const result = await db.run('INSERT INTO tbl(col) VALUES (:col)', {
':col': 'something'
})
更新行
const result = await db.run(
'UPDATE tbl SET col = ? WHERE col = ?',
'foo',
'test'
)
/*
{
// number of rows changed
changes: 1,
// instance of `sqlite#Statement`
// which is a wrapper around `sqlite3#Statement`
stmt: <Statement>
}
*/
准备好的声明
// stmt is an instance of `sqlite#Statement`
// which is a wrapper around `sqlite3#Statement`
const stmt = await db.prepare('SELECT col FROM tbl WHERE 1 = ? AND 5 = ?5')
await stmt.bind({ 1: 1, 5: 5 })
let result = await stmt.get()
// { col: 'some text' }
const stmt = await db.prepare(
'SELECT col FROM tbl WHERE 13 = @thirteen ORDER BY col DESC'
)
const result = await stmt.all({ '@thirteen': 13 })
each()
each()
与其他操作相比有点不同。
函数签名如下所示:
async each (sql, [...params], callback)
-
callback(err, row)
当数据库有一行要返回时触发 - 当所有行都返回并返回行数时,promise 会解析。
const rowsCount = await db.each(
'SELECT col FROM tbl WHERE ROWID = ?',
[2],
(err, row) => {
if (err) {
throw err
}
// row = { col: 'other thing' }
}
)
// rowsCount = 1
获取驱动实例
如果您需要调用尚不支持的方法,则很有用。
const rawDb = db.getDatabaseInstance()
const rawStatement = stmt.getStatementInstance()
关闭数据库
await db.close()
ES6 标记的模板字符串
该模块与sql-template-strings兼容。
import SQL from 'sql-template-strings'
const book = 'harry potter';
const author = 'J. K. Rowling';
const data = await db.all(SQL`SELECT author FROM books WHERE name = ${book} AND author = ${author}`);
迁移
这个模块带有一个轻量级的迁移 API,可以处理基于 SQL 的迁移文件
使用默认配置,您可以migrations/
在您的项目中创建一个包含 SQL 文件的目录,并调用该migrate()
方法对数据库运行该目录中的 SQL。
有关migrations/
示例,请参阅此项目的文件夹。
await db.migrate({
/**
* If true, will force the migration API to rollback and re-apply the latest migration over
* again each time when Node.js app launches.
*/
force?: boolean
/**
* Migrations table name. Default is 'migrations'
*/
table?: string
/**
* Path to the migrations folder. Default is `path.join(process.cwd(), 'migrations')`
*/
migrationsPath?: string
})
打字稿技巧
从 sqlite 导入接口
import { ISqlite, IMigrate } from 'sqlite'
有关更多详细信息,请参阅定义。
指定特定数据库驱动程序的类型
// Assuming you have @types/sqlite3 installed
import sqlite3 from 'sqlite3'
// sqlite3.Database, sqlite3.Statement is the default if no explicit generic is specified
await open<sqlite3.Database, sqlite3.Statement>({
filename: ':memory'
})
使用泛型在行上获得更好的类型
大多数方法允许使用泛型
来指定返回数据的数据类型。这允许您的 IDE 执行更好的自动完成和打字稿编译器执行更好的静态类型分析。
获取示例
interface Row {
col: string
}
// result will be of type Row, allowing Typescript supported IDEs to autocomplete on the properties!
const result = await db.get<Row>('SELECT col FROM tbl WHERE col = ?', 'test')
所有示例
interface Row {
col: string
}
// Result is an array of rows, you can now have array-autocompletion data
const result = await db.all<Row[]>('SELECT col FROM tbl')
result.each((row) => {
// row should have type information now!
})
API 文档
有关docs
完整文档,请参阅目录。
管理工具
- Beekeeper Studio:开源 SQL 编辑器和数据库管理器
- 适用于 SQLite 的 DB 浏览器:基于桌面的浏览器。
- datasette:Datasette 是一种用于探索和发布数据的工具。启动一个服务器,为您的 SQLite 数据提供 Web 界面。
- SQLite Studio:一个免费的、开源的、多平台的 SQLite 数据库管理器,用 C++ 编写,使用 Qt 框架。
- HeidiSQL:功能齐全的数据库编辑器。
- DBeaver:功能齐全的多平台数据库工具和设计器。
替代 SQLite 库
此库及其主要支持的库sqlite3
可能不是最适合您的用例的库。您可能想尝试这些其他 SQLite 库:
- Better -sqlite3:作为 Node.js 中 SQLite3 的最快和最简单的库,它本身就是一个例子。
- sql.js : SQLite 编译成 Webassembly。
-
sqlite3-offline:
sqlite3
如果您的机器无法编译,则提供预编译的二进制文件。应该主要与这个库兼容。
如果您认识任何其他人,请随时打开 PR 将他们添加到列表中。
参考
- 在 Medium.com 上使用 SQLite 和 Node.js 进行快速原型设计
- SQLite 文档,例如SQLite.org 上的SQL 语法、数据类型等
- ES6 标记sql-template-strings。
支持
- 加入Gitter 上的#node-sqlite聊天室以了解项目的最新情况
- 加入Freenode 上的#sqlite IRC 聊天室,讨论有关 SQLite 的一般性讨论
执照
MIT 许可证 © 2020 年至今 Kriasoft / Theo Gravity。版权所有。
用