Search code examples
javascriptnode.jselectronnode-sqlite3

SQLite 3 returning undefined value after inserted


I am developing electron app with sqlite 3 Database. I would like to get Last inserted ID after save data in database.

i have run below query but call result always showing undefined. can anybody help me to solve this issue?

db.run(`INSERT INTO  myTable (data1, data2) VALUES (aa, bb)`, (err) => {
            console.log(this.lastID)
            if (err) {
                console.log(err)
            } else {

                console.log( this.lastID)
            }

Data base inserted successfully but result, this.lastID result is undefine.


Solution

  • It's because you are using arrow syntax. Arrow syntax setting the this context to the parent. You should do:

    db.run(`INSERT INTO  myTable (data1, data2) VALUES (aa, bb)`, function (err)  {  
                console.log(this.lastID)
                if (err) {
                    console.log(err)
                } else {
    
                    console.log( this.lastID)
                })
    

    The call, apply and bind methods are NOT suitable for Arrow functions -- as they were designed to allow methods to execute within different scopes -- because Arrow functions establish "this" based on the scope the Arrow function is defined within.

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions