sqlite get row id after insert nodejs

To achieve this in Node.js, you can use the sqlite3 package to interact with SQLite databases. You can get the row id after an insert operation by using the lastID property provided by the sqlite3 module. Here's a step-by-step explanation of how to do this:

  1. First, you need to install the sqlite3 package by running the following command in your Node.js project directory:
npm install sqlite3
  1. Once the package is installed, you can create a new Node.js file (e.g., app.js) and require the sqlite3 module at the beginning of your file:
const sqlite3 = require('sqlite3').verbose();
  1. Next, you need to open a connection to your SQLite database using the sqlite3.Database constructor and specify the database file path. You can also provide a callback function to handle the database connection:
const db = new sqlite3.Database('your-database-file.db', (err) => {
  if (err) {
    console.error(err.message);
  }
  console.log('Connected to the database.');
});
  1. After establishing the connection, you can perform an insert operation using the run method, and then access the last inserted row id using the lastID property:
const insertSql = 'INSERT INTO your_table_name(column1, column2) VALUES (?, ?)';
const values = ['value1', 'value2'];

db.run(insertSql, values, function(err) {
  if (err) {
    return console.error(err.message);
  }
  console.log(`A new row has been inserted with row id ${this.lastID}`);
});
  1. Finally, you should close the database connection when you're done using the close method:
db.close((err) => {
  if (err) {
    console.error(err.message);
  }
  console.log('Database connection closed.');
});

By following these steps, you can successfully insert a row into an SQLite database using Node.js and retrieve the row id of the inserted record.