@6river/sqlite 中文文档教程

发布于 4年前 浏览 23 项目主页 更新于 3年前

SQLite Client for Node.js Apps

NPM 版本NPM 下载构建状态依赖状态Online Chat

添加 ES6 承诺和基于 SQL 的迁移 API 的包装器库 sqlite3文档).


想要加强您的核心 JavaScript 技能并掌握 ES6?
我个人会推荐 Wes 的这个很棒的 ES6 课程老板。


How to Install

$ npm install sqlite --save

How to Use

注意:对于 Node.js v5 及以下版本,请使用 var db = require('sqlite/legacy');

此模块与原始 sqlite3 库 (docs) 具有相同的 API, 除了它的所有 API 方法都返回 ES6 Promises 并且不接受回调参数。

下面是一个如何使用 Node.js 的例子,ExpressBabel

import express from 'express';
import Promise from 'bluebird';
import sqlite from 'sqlite';

const app = express();
const port = process.env.PORT || 3000;
const dbPromise = sqlite.open('./database.sqlite', { Promise });

app.get('/post/:id', async (req, res, next) => {
  try {
    const db = await dbPromise;
    const [post, categories] = await Promise.all([
      db.get('SELECT * FROM Post WHERE id = ?', req.params.id),
      db.all('SELECT * FROM Category')
    ]);
    res.render('post', { post, categories });
  } catch (err) {
    next(err);
  }
});

app.listen(port);

ES6 tagged template strings

该模块兼容 sql-template-strings

import SQL from 'sql-template-strings';
import sqlite from 'sqlite';

const db = await sqlite.open('./database.sqlite');

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}`);

Cached DB Driver

如果你想启用数据库对象缓存

sqlite.open('./database.sqlite', { cached: true })

Migrations

这个模块带有一个轻量级的迁移 API,它可以与 基于SQL的迁移文件 如以下示例所示:

migrations/001-initial-schema.sql
-- Up
CREATE TABLE Category (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE Post (id INTEGER PRIMARY KEY, categoryId INTEGER, title TEXT,
  CONSTRAINT Post_fk_categoryId FOREIGN KEY (categoryId)
    REFERENCES Category (id) ON UPDATE CASCADE ON DELETE CASCADE);
INSERT INTO Category (id, name) VALUES (1, 'Business');
INSERT INTO Category (id, name) VALUES (2, 'Technology');

-- Down
DROP TABLE Category
DROP TABLE Post;
migrations/002-missing-index.sql
-- Up
CREATE INDEX Post_ix_categoryId ON Post (categoryId);

-- Down
DROP INDEX Post_ix_categoryId;
app.js (Node.js/Express)
import express from 'express';
import Promise from 'bluebird';
import sqlite from 'sqlite';

const app = express();
const port = process.env.PORT || 3000;

const dbPromise = Promise.resolve()
  .then(() => sqlite.open('./database.sqlite', { Promise }))
  .then(db => db.migrate({ force: 'last' }));

app.use(/* app routes */);

app.listen(port);

注意:对于开发环境,在处理数据库架构时,您可能需要设置 force: 'last'(默认 false)将强制迁移 API 回滚并重新应用 每次启动 Node.js 应用程序时,都会重新进行最新迁移。

Multiple Connections

open 方法解析为 db 实例,可用于引用多个打开的数据库。

ES6

import sqlite from 'sqlite';

Promise.all([
  sqlite.open('./main.sqlite', { Promise }),
  sqlite.open('./users.sqlite', { Promise })
]).then(function([mainDb, usersDb]){
  ...
});

ES7+ Async/Await

import sqlite from 'sqlite';

async function main() {
  const [mainDb, usersDb] = await Promise.all([
    sqlite.open('./main.sqlite', { Promise }),
    sqlite.open('./users.sqlite', { Promise })
  ]);
  ...
}
main();

References

Related Projects

Support

  • Join #node-sqlite chat room on Gitter to stay up to date regarding the project
  • Join #sqlite IRC chat room on Freenode about general discussion about SQLite

License

MIT 许可证 © 2015 年至今 Kriasoft。 版权所有。


Konstantin Tarkus (@koistya) 用 ♥ 制作、Theo Gravity贡献者< /a>

SQLite Client for Node.js Apps

NPM versionNPM downloadsBuild StatusDependency StatusOnline Chat

A wrapper library that adds ES6 promises and SQL-based migrations API to sqlite3 (docs).


???? Want to strengthen your core JavaScript skills and master ES6?
I would personally recommend this awesome ES6 course by Wes Bos.


How to Install

$ npm install sqlite --save

How to Use

NOTE: For Node.js v5 and below use var db = require('sqlite/legacy');.

This module has the same API as the original sqlite3 library (docs), except that all its API methods return ES6 Promises and do not accept callback arguments.

Below is an example of how to use it with Node.js, Express and Babel:

import express from 'express';
import Promise from 'bluebird';
import sqlite from 'sqlite';

const app = express();
const port = process.env.PORT || 3000;
const dbPromise = sqlite.open('./database.sqlite', { Promise });

app.get('/post/:id', async (req, res, next) => {
  try {
    const db = await dbPromise;
    const [post, categories] = await Promise.all([
      db.get('SELECT * FROM Post WHERE id = ?', req.params.id),
      db.all('SELECT * FROM Category')
    ]);
    res.render('post', { post, categories });
  } catch (err) {
    next(err);
  }
});

app.listen(port);

ES6 tagged template strings

This module is compatible with sql-template-strings.

import SQL from 'sql-template-strings';
import sqlite from 'sqlite';

const db = await sqlite.open('./database.sqlite');

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}`);

Cached DB Driver

If you want to enable the database object cache

sqlite.open('./database.sqlite', { cached: true })

Migrations

This module comes with a lightweight migrations API that works with SQL-based migration files as the following example demonstrates:

migrations/001-initial-schema.sql
-- Up
CREATE TABLE Category (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE Post (id INTEGER PRIMARY KEY, categoryId INTEGER, title TEXT,
  CONSTRAINT Post_fk_categoryId FOREIGN KEY (categoryId)
    REFERENCES Category (id) ON UPDATE CASCADE ON DELETE CASCADE);
INSERT INTO Category (id, name) VALUES (1, 'Business');
INSERT INTO Category (id, name) VALUES (2, 'Technology');

-- Down
DROP TABLE Category
DROP TABLE Post;
migrations/002-missing-index.sql
-- Up
CREATE INDEX Post_ix_categoryId ON Post (categoryId);

-- Down
DROP INDEX Post_ix_categoryId;
app.js (Node.js/Express)
import express from 'express';
import Promise from 'bluebird';
import sqlite from 'sqlite';

const app = express();
const port = process.env.PORT || 3000;

const dbPromise = Promise.resolve()
  .then(() => sqlite.open('./database.sqlite', { Promise }))
  .then(db => db.migrate({ force: 'last' }));

app.use(/* app routes */);

app.listen(port);

NOTE: For the development environment, while working on the database schema, you may want to set force: 'last' (default false) that will force the migration API to rollback and re-apply the latest migration over again each time when Node.js app launches.

Multiple Connections

The open method resolves to the db instance which can be used in order to reference multiple open databases.

ES6

import sqlite from 'sqlite';

Promise.all([
  sqlite.open('./main.sqlite', { Promise }),
  sqlite.open('./users.sqlite', { Promise })
]).then(function([mainDb, usersDb]){
  ...
});

ES7+ Async/Await

import sqlite from 'sqlite';

async function main() {
  const [mainDb, usersDb] = await Promise.all([
    sqlite.open('./main.sqlite', { Promise }),
    sqlite.open('./users.sqlite', { Promise })
  ]);
  ...
}
main();

References

Related Projects

Support

  • Join #node-sqlite chat room on Gitter to stay up to date regarding the project
  • Join #sqlite IRC chat room on Freenode about general discussion about SQLite

License

The MIT License © 2015-present Kriasoft. All rights reserved.


Made with ♥ by Konstantin Tarkus (@koistya), Theo Gravity and contributors

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文