使用 Node.js 读取 SQLite 数据库

Read SQLite database with Node.js

有了这个 SQLite 数据库,我正在尝试从中读取数据。所以,我想阅读来自 table Athlete 的前 3 列。

这是代码(app.js):

var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('ocs_athletes');

db.serialize(function () {
  db.each('SELECT athlete_id, name, surname FROM Athlete', function (err, row) {
    console.log('User: ', row.athlete_id, row.name, row.surname);
  });
});

db.close();

文件 app.js 与 db 文件位于同一文件夹中 - ocs_athletes。

运行 in cmd node app.js returns 这个错误信息:

/home/dd/Documents/Projects/OCSapp/app.js:6
    console.log('User: ', row.athlete_id, row.name, row.surname);
                              ^

TypeError: Cannot read property 'athlete_id' of undefined
    at /home/dd/Documents/Projects/OCSapp/app.js:6:31
    at replacement (/home/dd/Documents/Projects/OCSapp/node_modules/sqlite3/lib/trace.js:25:27)
    at Statement.errBack (/home/dd/Documents/Projects/OCSapp/node_modules/sqlite3/lib/sqlite3.js:14:21)

为什么会这样?

尝试像这样连接到数据库。

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

给出 .db 文件的路径。这会起作用。

共有三种打开方式:

sqlite3.OPEN_READONLY: 以只读方式打开数据库。

sqlite3.OPEN_READWRITE : 打开数据库进行读写。

sqlite3.OPEN_CREATE:打开数据库,如果数据库不存在,则新建一个数据库。

打开chinook示例数据库进行读写,可以按如下方式进行:

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