4

【笔记】Nodejs 操作 Sqlite3 数据库

 10 months ago
source link: https://loli.fj.cn/2023/07/07/Nodejs%E6%93%8D%E4%BD%9CSqlite3%E6%95%B0%E6%8D%AE%E5%BA%93/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

【笔记】Nodejs 操作 Sqlite3 数据库

2023-07-07

Nodejs 操作 Sqlite3 数据库学习笔记

npm install sqlite3
const sqlite3 = require('sqlite3').verbose();

<filename>.db:数据库文件

const db = new sqlite3.Database('<filename>.db', sqlite3.OPEN_READWRITE, function (err) {
// 数据库连接失败
if (err) {
return console.log(err.message)
}
// 数据库连接成功
...
}
)

执行没有返回值的 SQL 语句

  • 通过 thischanges 字段值可以获取成功执行的 SQL 条数

<sql>:SQL 语句

db.run("<sql>", [], function (err) {
// SQL执行失败
if (err) {
return console.log(err.message);
}
// SQL执行成功
...
})
  • 通过 ? 作为占位符
db.run("INSERT INTO 数据表名(字段名) VALUES(?)", ["占位符的值"], function (err) {
// SQL执行失败
if (err) {
return console.log(err.message);
}
// SQL执行成功
...
})

执行有返回值的 SQL 语句

<sql>:SQL 语句

db.all("<sql>", [], function (err, rows) {
// SQL执行失败
if (err) {
return console.log(err.message);
}
// 查询成功
console.log(rows);
})

简明 Node.js 小册子


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK