2

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.

Shafeeque OT
  • 83
  • 1
  • 8

1 Answers1

2

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

Aminadav Glickshtein
  • 23,232
  • 12
  • 77
  • 117
  • Brothers, can you help me to solve this issue. https://stackoverflow.com/questions/71265088/cannot-find-module-sqlite3-after-build-exe-with-electron-builder – Shafeeque OT Mar 01 '22 at 11:28