Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sqlite3 create database with callback using Node

Tags:

node.js

sqlite

I've searched on how to create a sqlite3 database with a callback in Node.js and have not been able to find any links. Can someone point me towards documentation or provide a 2-3 line code sample to achieve the following:

  • Create a sqlite3 database and catch an error if the creation fails for any reason.

Here is what I've tried:

     let dbCreate = new sqlite3.Database("./user1.db", sqlite3.OPEN_CREATE, function(err){

        if(!err){
           logger.infoLog("Successfully created DB file: " + dbFileForUser + " for user: " + username );
        } else {
           logger.infoLog("Failed to create DB file: " + dbFileForUser + ". Error: " + err );
        }
     });

     dbHandler[username]  = dbCreate;

When I execute this, I get the following error: "Failed to create DB file: ./database/user1.db. Error: Error: SQLITE_MISUSE: bad parameter or other API misuse"

This call without callback works just fine.

var customDB = new sqlite3.Database("./custom.db", sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE);

But in this, I will not know if I run into any errors while creating the Database.

like image 703
Curious101 Avatar asked Jul 05 '18 05:07

Curious101


People also ask

How do I connect to a SQLite database in node?

To connect to an SQLite database, you need to: First, import the sqlite3 module. Second, call the Database() function of the sqlite3 module and pass the database information such as database file, opening mode, and a callback function.

How do I create a DB file in sqlite3?

To create a new database in SQLite you need to specify databases when opening SQLite, or open an existing file using . open . You can use the . database command to see a list of existing databases.

What is sqlite3 verbose?

sqlite3.verbose()Sets the execution mode to verbose to produce long stack traces. There is no way to reset this. See the wiki page on debugging for more information.


1 Answers

Try this:

let userDB = new sqlite3.Database("./user1.db", 
    sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE, 
    (err) => { 
        // do your thing 
    });

Example.

like image 177
Irvin Sandoval Avatar answered Sep 24 '22 20:09

Irvin Sandoval