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

Robert C. Holland picture Robert C. Holland · Aug 10, 2017 · Viewed 7k times · Source

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.

Answer

Tim Biegeleisen picture Tim Biegeleisen · Aug 10, 2017

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
});