How to connect sqlite3 database using Node.js ?


To connect to a SQLite3 database using Node.js, you can use the sqlite3 module. Here are the steps to connect to a SQLite3 database using Node.js:

  • Install the sqlite3 module using npm:
npm install sqlite3
  • Require the sqlite3 module in your Node.js application:
const sqlite3 = require('sqlite3').verbose();
  • Create a new sqlite3.Database object and connect to the database:
const db = new sqlite3.Database('path/to/database.sqlite');

Replace 'path/to/database.sqlite' with the path to your SQLite3 database file.

  • Perform database operations using the db object. For example, you can execute SQL queries using the db.all() method:
db.all('SELECT * FROM users', (err, rows) => {
  if (err) {
    console.error(err.message);
  }
  console.log(rows);
});

This will execute the SQL query SELECT * FROM users and log the results to the console.

Here's an example of a complete Node.js application that connects to a SQLite3 database and performs a query:

const sqlite3 = require('sqlite3').verbose();

const db = new sqlite3.Database('path/to/database.sqlite');

db.all('SELECT * FROM users', (err, rows) => {
  if (err) {
    console.error(err.message);
  }
  console.log(rows);
});

db.close();

This application connects to the SQLite3 database located at 'path/to/database.sqlite', executes the SQL query SELECT * FROM users, logs the results to the console, and then closes the database connection.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.