nodejs sqlite3 db. insert
const sqlite3 = require('sqlite3').verbose();
// Connect to the database
const db = new sqlite3.Database(':memory:');
// Create a table
db.serialize(() => {
db.run('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)');
});
// Insert data into the table
db.serialize(() => {
const stmt = db.prepare('INSERT INTO users (name) VALUES (?)');
stmt.run('John Doe');
stmt.finalize();
});
// Close the database connection
db.close();
Explanation:
- Import the sqlite3 module.
- Create a new instance of SQLite database in memory.
- Define a table named "users" with columns 'id' (INTEGER, PRIMARY KEY) and 'name' (TEXT).
- Prepare an SQL statement to insert data into the 'users' table.
- Bind the value 'John Doe' to the prepared statement and execute it to insert a new row.
- Finalize the statement to release resources associated with it.
- Close the connection to the SQLite database.