4

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?

8
  • Why to use db. serialize ? Commented Jul 12, 2020 at 17:49
  • I don't know, it's the first time I'm using SQLite with Node and this is how I've found in a tutorial. should I do it differently? Commented Jul 12, 2020 at 17:50
  • As I can see in documentation. The each() method executes an SQL query with specified parameters and calls a callback for every row in the result set.. What do you want to do get all rows or specific rows ? Commented Jul 12, 2020 at 18:03
  • doesn't matter, all of them are fine. I was looking at this tutorial and did it like that youtube.com/watch?v=GCuJi2kzaqI Commented Jul 12, 2020 at 18:04
  • Have just tried printing just row what data you are getting in return. Commented Jul 12, 2020 at 18:09

1 Answer 1

7

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.');
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.