I want to get the row id immediately after creating a new record in a table, I've seen that you can use sql along the lines of
INSERT INTO table(value) VALUES (?) RETURNING *
to do that but I don't know how to get the data out of the statement afterwards.
So far I've tried
sql = ("INSERT INTO table(value) VALUES (?) RETURNING *");
db.run(sql, [value]), (err, row) => {
if (err) return console.error(err.message)
value = row.value
console.log("value id is:",value)
}
but that doesn't work.
Any help would be greatly appreciated!
I think you can access the this.lastID
in the callback when no errors occurs. Like discussed here.
Pay attention to your code, has some typos. See the documentation SQLite run. Is all there.
db.run(`INSERT INTO table(name) VALUES(?)`, ['value'], function(err) {
if (err) {
console.log(err.message);
}
// get the last insert id
console.log(`A row has been inserted with rowid ${this.lastID}`);
});
Last but not least, don't use arrow function in the callback. Like said in the doc too.