[ACCEPTED]-Sqlite SQLITE_MISUSE error in node.js script-sqlite

Accepted answer
Score: 12

You've got a race condition; it's possible 18 that your last query (whose callback closes 17 the connection) will finish before one of 16 the earlier queries did, and that will, needless 15 to say, hose the earlier query. You need 14 to rework your code so that the last query 13 to finish, rather than the last query to start, closes 12 the connection (e.g set a counter to the 11 number of queries and have each query decrement 10 it when it finishes. The one that decrements 9 it to zero closes the connection).

You might 8 also want to look at the serialize method that's 7 available on database objects. Right now 6 your initialization queries are all independent 5 of each other, but if you started using 4 foreign-key constraints you'd have trouble 3 if the referenced table hadn't been created 2 yet, so you'd need to force the order of 1 execution.

Score: 2

Use Promises.

Here I get data from one table and use this 5 data to create a statement for inserting 4 in another table.

serialize() do run 1-by-1 but I wanted 3 the response from one query to be used in 2 another. If I put 2nd query in callback of 1 1st then it gives the SQLITE_MISUSE error


    // QUERY 1 (SELECT) - Get data 
    let promiseGetFoo = new Promise((resolve, reject) => {
      db.all("SELECT * FROM foo", (err, rows) => {
        if (err) {
        } else {

    // QUERY 2 (INSERT) - Use data from QUERY 1
    promiseGetFoo.then((res) => {
      let stmt = (res) => { 
        // code to create INSERT statement 
      db.run(stmt, (err) => {
        if(err) console.log(err);
        else console.log(">>> Insert DONE");


let closeDb = () => {
    db.close() ;

More Related questions