Robert C. Holland
Robert C. Holland

Reputation: 1813

How to SELECT / get all rows with node-sqlite3?

I am trying to get all / more than one row of data out of sqlite3 database that I previously entered and ensured that it(data) is present. With db as the database object, my attempt looks like this:

 db.get
    (
        'SELECT * FROM my_table',
        (err, rows) =>
        {
            if(rows && err === null)
            {
                console.log(rows);
            }
            else
            {
                console.log('Error', err);
            }
        }
    )

Above always returns a single object with 1 row of data.

Upvotes: 4

Views: 14833

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522752

The issue here is that db.get() will only return the first row from the result set. From the documentation:

Runs the SQL query with the specified parameters and calls the callback with the first result row afterwards.

If you want to return the entire result set, use db.all() instead:

db.all("SELECT * FROM my_table", function(err, rows) {  
    rows.forEach(function (row) {  
        console.log(row.col1, row.col2);    // and other columns, if desired
    })  
});

You could also use db.each() here:

db.each("SELECT * FROM my_table", function(err, row) {
    console.log(row.col1, row.col2);    // and other columns, if desired
});

Upvotes: 17

Related Questions