Node - Js SQLite Tutorial - Connection & CRUD - Techiediaries
Node - Js SQLite Tutorial - Connection & CRUD - Techiediaries
In this tutorial, you'll learn to use SQLite in Node.js. We'll be using the node-sqlite3
driver for Node.js, hich provides an asynchronous, non-blocking SQLite3 bindings for
Node.js, to connect to a sqlite database and perform CRUD operations.
$ mkdir node-sqlite-crud
Next, navigate inside your project's folder and generate a package.json file with default
values:
$ cd node-sqlite-crud
$ npm init -y
Next, you need to create an app.js file inside your project's folder. For now, leave it
empty.
https://www.techiediaries.com/node-sqlite-crud/ 1/3
17/08/2023, 09:15 Node.js SQLite Tutorial — Connection & CRUD | Techiediaries
We create a mydb.sqlite database file inside the current project's folder using the
sqlite3.Database() method. We pass in a filename and a function that will be called
once the database is created or an error is occurred.
If no error occurs (i.e err == null), we need to add any code for creating database
tables and interacts with the database.
Now let's define the createTable() method which will be called once the database file is
created without any errors:
We use the db.run() method to execute SQL queries against the SQLite3 database.
When the operation is done a the insertData() callback passed as a second parameter
will be called.
Next we need to define the insertData() method and add any table inserts in it.
https://www.techiediaries.com/node-sqlite-crud/ 2/3
17/08/2023, 09:15 Node.js SQLite Tutorial — Connection & CRUD | Techiediaries
Similarly, you can delete and update data using the SQL DELETE and UPDATE statements.
read = () => {
console.log("Read data from contacts");
db.all("SELECT rowid AS id, name FROM contacts", function(err, rows) {
rows.forEach(function (row) {
console.log(row.id + ": " + row.name);
});
});
}
You can finally close the database using the following method:
db.close();
Conclusion
In this tutorial, we've seen how to use SQLite 3 in Node.js to perform simple CRUD
operations. See the official repository of node-sqlite3 for more details.
https://www.techiediaries.com/node-sqlite-crud/ 3/3