1

Having this SQLite DB I'm trying to read the data from it. So, from table Athlete I want to read the first 3 columns.

enter image description here

This is the code (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();

The file app.js is in the same folder as the db file - ocs_athletes.

Running in cmd node app.js returns this error message:

/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)

Why is this happening?

Leo Messi
  • 5,157
  • 14
  • 63
  • 125

1 Answers1

4

Try connecting to db like this.

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

Give path of .db file. This will work.

There are three opening modes:

sqlite3.OPEN_READONLY: open the database for read-only.

sqlite3.OPEN_READWRITE : open the database for reading and writting.

sqlite3.OPEN_CREATE: open the database, if the database does not exist, create a new database.

To open the chinook sample database for read and write, you can do it as follows:

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.');
});
xMayank
  • 1,875
  • 2
  • 5
  • 19