node js sqlite3
To establish a connection to a SQLite database using Node.js and the sqlite3 module, you would need to follow these steps:
- Install the sqlite3 module: First, you need to install the sqlite3 module in your Node.js project. You can do this by running the following command in your project's terminal or command prompt:
npm install sqlite3
- Import the sqlite3 module: Once the installation is complete, you can import the sqlite3 module into your Node.js script by using the
require
keyword:
const sqlite3 = require('sqlite3');
- Create a database connection: To create a connection to the SQLite database, you can use the
new sqlite3.Database()
constructor function, passing the path to your database file as an argument:
const db = new sqlite3.Database('path/to/database.db');
- Execute SQL queries: Now that you have a database connection, you can execute SQL queries. The
db.run()
method is commonly used to execute SQL statements that don't return any results, such as creating tables or inserting data:
db.run('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)');
To execute SQL queries that return results, such as selecting data from a table, you can use the db.all()
method:
db.all('SELECT * FROM users', (err, rows) => {
// Handle the query results here
});
- Close the database connection: After you have finished working with the database, it's important to close the connection to free up resources. You can use the
db.close()
method to close the database connection:
db.close((err) => {
// Handle any errors that occur during the closing process
});
Remember to handle any errors that may occur during the execution of your code to ensure smooth operation.