我正在开发应用程序node.js.在那我愿意SQLite用作嵌入式数据库.我在网上搜索了SQLitenpm模块.我找到了各种模块:
从文档和其他来源,我明白(1)同步操作,而(2)和(3)异步工作.所以,我放弃了使用计划(1).
现在,我想知道(2)和(3)之间有什么区别,哪一个应该是首选?我google了很多,但找不到多少帮助.
Tre*_*xon 34
使用https://github.com/mapbox/node-sqlite3.它是异步的(几乎是必须的),它是最积极维护的,它在GitHub上拥有最多的星星.
对于我的架构,同步better-sqlite3似乎更好:
https://www.npmjs.com/package/better-sqlite3
import express from 'express';
import db from 'sqlite'; // <=
import Promise from 'bluebird';
const app = express();
const port = process.env.PORT || 3000;
app.get('/posts', async (req, res, next) => {
try {
const posts = await db.all('SELECT * FROM Post LIMIT 10'); // <=
res.send(posts);
} catch (err) {
next(err);
}
});
Promise.resolve()
// First, try to open the database
.then(() => db.open('./database.sqlite', { Promise }) // <=
// Update db schema to the latest version using SQL-based migrations
.then(() => db.migrate({ force: 'last' }) // <=
// Display error message if something went wrong
.catch((err) => console.error(err.stack))
// Finally, launch the Node.js app
.finally(() => app.listen(port));
Run Code Online (Sandbox Code Playgroud)
注意:上面的示例仅适用于Node.js v6 和更新版本(假设代码中使用的import和async/await语言功能使用Babel 进行了转换)。对于较早版本的 Node.js,请使用var db = require('sqlite/legacy');.
| 归档时间: |
|
| 查看次数: |
33649 次 |
| 最近记录: |