Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing SQLite3 Database in NodeJS

Tags:

node.js

sqlite

I'm creating a database using SQLite3 in NodeJS. I've succesfully been able to create the database with a table and insert data. If I'm in that same file and I do a select to log the data from my table it works. My question is how can I run a query on the database from another js file? I've tried using the module way but had no luck. Let's say m file that creates the databse is called

db.js

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

db.serialize(function() {

    db.run("CREATE TABLE if not exists parameters (path TEXT)");
    var stmt = db.prepare("INSERT INTO parameters VALUES (?)");


    stmt.run("test paramter");
    stmt.finalize();

   db.each("SELECT path FROM parameters", function(err, row) {
       console.log(row.path);
    });
});
db.close();

Then I have a file called

update.js

How could I run a query

   db.each("SELECT path FROM parameters", function(err, row) {
        console.log(row.path);
    });

inside this js file instead?

like image 560
SaSquadge Avatar asked Apr 18 '26 18:04

SaSquadge


1 Answers

I solved it by adding __dirname

    const sqlite3 = require('sqlite3').verbose();                                                                                                                                           
const db = new sqlite3.Database(__dirname+'/database.sqlite');                                                                                                                          
db.each("SELECT id FROM loan;", function(err, row) {                                                                                                                                    
      console.log(row);                                                                                                                                                                 
}); 
like image 136
Sam Avatar answered Apr 20 '26 09:04

Sam