How to connect to SQLite using Node.js

This article describes how to connect to a SQLite database using Node.js.

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:

  1. Log in to your account using SSH.
  2. 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

Did you find this article helpful? Then you'll love our support. Experience the A2 Hosting difference today and get a pre-secured, pre-optimized website. Check out our web hosting plans today.

We use cookies to personalize the website for you and to analyze the use of our website. You consent to this by clicking on "I consent" or by continuing your use of this website. Further information about cookies can be found in our Privacy Policy.