sqlite3 create database with callback using Node

后端 未结 2 1875
悲哀的现实
悲哀的现实 2020-12-18 05:02

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

相关标签:
2条回答
  • 2020-12-18 05:31

    Try this:

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

    Example.

    0 讨论(0)
  • 2020-12-18 05:39

    @Irvin is correct, we can have a look at http://www.sqlitetutorial.net/sqlite-nodejs/connect/ and check it says if you skip the 2nd parameter, it takes default value as sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE and in this case if database does not exist new database will be created with connection.

    sqlite3.OPEN_READWRITE: It is to open database connection and perform read and write operation.

    sqlite3.OPEN_CREATE : It is to create database (if it does not exist) and open connection.

    So here is the first way where you have to skip the 2nd parameter and close the problem without an extra effort.

    const sqlite3 = require("sqlite3").verbose();
    
    let db = new sqlite3.Database('./user1.db', (err) => {
        if (err) {
            console.error(err.message);
        } else {
            console.log('Connected to the chinook database.|');
        }
    });
    
    
    db.close((err) => {
        if (err) {
            return console.error(err.message);
        }
        console.log('Close the database connection.');
    });
    

    And this is the 2nd way to connect with database (already answered by @Irvin).

    const sqlite3 = require("sqlite3").verbose();
    
    let db = new sqlite3.Database('./user1.db', sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE
    , (err) => {
        if (err) {
            console.error(err.message);
        } else {
            console.log('Connected to the chinook database.');
        }
    });
    
    
    db.close((err) => {
        if (err) {
            return console.error(err.message);
        }
        console.log('Close the database connection.');
    });
    
    0 讨论(0)
提交回复
热议问题