Connecting to SQLite using Node.js
This article describes how to connect to a SQLite database using Node.js.
This article describes how to connect to a SQLite database using Node.js.
Tip
Node.js must already be installed on your account. For information about how to install Node.js, please see this article.
Connecting to SQLite using Node.js
The sqlite3 package includes all of the functionality you need to access and work with SQLite databases in Node.js. Before you can do this, however, you must install the sqlite3 package on your account. To do this, follow these steps:
-
Log in to your account using SSH.
-
Type the following commands:
cd ~ npm install sqlite3
Code sample
After you install the sqlite3 package, you are ready to work with SQLite databases and manipulate data in them. The following sample Node.js code demonstrates how to do this:
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database('test.db');
db.serialize(() => {
db.run("CREATE TABLE employees (firstname varchar(32), lastname varchar(32), title varchar(32));");
db.run("INSERT INTO employees VALUES('Kelly', 'Koe', 'Engineer');");
db.each("SELECT firstname, lastname FROM employees;", (err, row) => {
console.log(row.firstname + " " + row.lastname);
});
});
db.close();
In this example, we first instantiate a Database object that creates a SQLite database in the test.db file.
After we have a Database object associated with the database, we can run raw SQL statements (such as CREATE TABLE, INSERT INTO, and SELECT).
Finally, we call the close() method to close the connection to the database.
More Information
- For more information about the sqlite3 package, please visit https://www.npmjs.com/package/sqlite3.
- For more information about the sqlite3 API, please visit https://github.com/TryGhost/node-sqlite3/wiki/API.
Updated 3 days ago