sqlite for node

本文详细介绍了如何使用Node.js连接和操作SQLite3数据库,包括安装SQLite3模块,连接到内存和磁盘数据库,以及基本的数据查询过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

sqlite for node

1.intro

to understand how sqlite3 works, we can know it from following tutorials:

  • 安装
  • 如何连接到数据库: 这部分将展示如何连接到内存数据库和磁盘数据库。
  • 如何从表中查询数据:这部分将告诉你多种办法进行查询
  • …暂略,后面打算借助实例再进行记录,或许再看看sequelize

2.install

npm install sqlite3

After installing the sqlite3 module, you are ready to connect to a SQLite database from a Node.js application.

3.connecting to database

连接到内存数据库
  1. 第一步:导入sqlite3模块
const sqlite3 = require("sqlite3").verbose();

Notice that the execution mode is set to verbose to produce long stack traces.
注意,当执行模式设为verbose时,将产生很长的堆栈追踪。

  1. 第二步:构造Database对象

database()函数有两个个参数:

  • 数据库文件:内存数据库或磁盘数据库文件
  • callback function
let db = new sqlite3.Database(':memory:', (err) => {
  if (err) {
    return console.error(err.message);
  }
  console.log('Connected to the in-memory SQlite database.');
});

回调函数的第一个参数是err,如果在打开数据库的过程中发生了错误,err将不为null。

  1. 第三步:关闭数据库
db.close();

与Database()相似的是,close()也具有相似的特征

db.close((err) => {
  if (err) {
    return console.error(err.message);
  }
  console.log('Close the database connection.');
});
  1. 一次完整的操作
// connect.js
const sqlite3 = require('sqlite3').verbose();
 
// open database in memory
let db = new sqlite3.Database(':memory:', (err) => {
  if (err) {
    return console.error(err.message);
  }
  console.log('Connected to the in-memory SQlite database.');
});
 
// close the database connection
db.close((err) => {
  if (err) {
    return console.error(err.message);
  }
  console.log('Close the database connection.');
});
连接到磁盘数据库

这个只需要把Database()函数中的第一个参数从’:memory:'改为db文件的路径即可。

let db = new sqlite3.Database('./db/disk.db', openmode, (err) => {
  if (err) {
    console.error(err.message);
  }
  console.log('Connected to the diskdatabase.');
});

这里注意在打开磁盘数据库时,Database函数有额外的参数 openmode

  1. sqlite3.OPEN_READONLY: 只读
  2. sqlite3.OPEN_READWRITE: 可读可写
  3. sqlite3.OPEN_CREATE: 当函数的第一个参数路径不存在时,则创建数据库文件
const sqlite3 = require('sqlite3').verbose();
 
// open the database
let db = new sqlite3.Database('./db/chinook.db', sqlite3.OPEN_READWRITE, (err) => {
  if (err) {
    console.error(err.message);
  }
  console.log('Connected to the chinook database.');
});
 
db.serialize(() => {
  db.each(`SELECT PlaylistId as id,
                  Name as name
           FROM playlists`, (err, row) => {
    if (err) {
      console.error(err.message);
    }
    console.log(row.id + "\t" + row.name);
  });
});
 
db.close((err) => {
  if (err) {
    console.error(err.message);
  }
  console.log('Close the database connection.');
});

上面的例子完整地展示了一次打开、查询、关闭磁盘数据库的过程。

接下来将介绍如何进行查询。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值