How to Create Table in SQLite3 Database using Node.js ?
Last Updated :
29 Jul, 2024
Creating a table in an SQLite database using Node.js involves several steps, including setting up a connection to the database, defining the table schema, and executing SQL commands to create the table. SQLite is a lightweight and serverless database that is widely used, especially in applications that need a simple and embedded database solution. Here's a step-by-step guide on how to create a table in SQLite using Node.js:
SQLite
SQLite is a self-contained, high-reliability, embedded, public-domain, SQL database engine. It is the most used database engine in the world. Let’s understand How to create a table in a SQLite3 database using Node.js.Â
Steps to Setup Project
Step 1: Make a folder structure for the project.
mkdir myapp
Step 2:Â Navigate to the project directory
cd myapp
Step 3: Initialize the NodeJs project inside the myapp folder.
npm init -y
Step 4: Install the necessary packages/libraries in your project using the following commands.
npm install express sqlite3
Project Structure:
The updated dependencies in package.json file will look like:
"dependencies": {
"express": "^4.19.2",
"sqlite3": "^5.1.7",
}
Step 1: Set Up Database Connection
Require the sqlite3
module and create a new SQLite database connection. You can also create an in-memory database or specify a file-based database.
const sqlite3 = require('sqlite3').verbose();
// Connect to a database (in this example, a new file-based database)
const db = new sqlite3.Database('mydatabase.db');
If the database file (mydatabase.db
in this example) does not exist, SQLite will create it when you connect to it.
Step 2: Define Table Schema
Define the schema of the table using SQL CREATE TABLE
statement. Specify the table name, column names, data types, and any constraints (such as primary keys or unique constraints).
// Define the SQL statement to create a table
const createTableSql = `
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL,
email TEXT UNIQUE NOT NULL,
password TEXT NOT NULL
)`;
// Execute the SQL statement to create the table
db.run(createTableSql, (err) => {
if (err) {
return console.error('Error creating table:', err.message);
}
console.log('Table created successfully');
});
In this example, a table named users
is created with columns id
, username
, email
, and password
. The id
column is set as the primary key with auto-increment, email
is marked as unique, and username
and password
are required (NOT NULL
).
Step 3: Execute SQL Commands
Use the db.run()
method to execute SQL commands. This method is used for SQL commands that don't return rows (like CREATE TABLE
, INSERT
, UPDATE
, DELETE
).
db.run(createTableSql, function(err) {
if (err) {
return console.error(err.message);
}
console.log('Table created successfully');
});
Example
Here's a complete example demonstrating how to create a SQLite database and a table using Node.js:
Node
// main.js
import x from 'sqlite3'
const sqlite3 = x.verbose();
// Connect to a database (in this example, a new file-based database)
const db = new sqlite3.Database('mydatabase.db');
// Define the SQL statement to create a table
const createTableSql = `
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL,
email TEXT UNIQUE NOT NULL,
password TEXT NOT NULL
)
`;
// Execute the SQL statement to create the table
db.run(createTableSql, function (err) {
if (err) {
return console.error('Error creating table:', err.message);
}
console.log('Table created successfully');
});
// Close the database connection
db.close((err) => {
if (err) {
return console.error(err.message);
}
console.log('Database connection closed');
});
Step to Run Application:Â Run the application using the following command from the root directory of the project
Similar Reads
How to Connect SQLite3 Database using Node.js ?
Connecting SQLite3 database with Node.js involves a few straightforward steps to set up and interact with the database. SQLite is a self-contained, serverless, zero-configuration, transactional SQL database engine, making it ideal for small to medium-sized applications. Hereâs how you can connect an
2 min read
How to update data in sqlite3 using Node.js ?
In this article, we are going to see how to update data in the sqlite3 database using node.js. So for this, we are going to use the run function which is available in sqlite3. This function will help us to run the queries for updating the data. SQLite is a self-contained, high-reliability, embedded,
4 min read
How to create new Mongodb database using Node.js ?
mongodb module: This Module is used to performing CRUD(Create Read Update Read) Operations in MongoDb using Node.js. We cannot make a database only. We have to make a new Collection to see the database. The connect() method is used for connecting the MongoDb server with the Node.js project. Please r
1 min read
How to Insert and Select Data in SQLite3 Database using Node.js ?
Inserting and selecting data in an SQLite3 database using Node.js involves connecting to the database, running SQL queries, and handling the results. SQLite is an excellent choice for small to medium-sized applications due to its simplicity and lightweight nature. This guide will walk you through th
3 min read
How to Connect to a MongoDB Database Using Node.js
MongoDB is a NoSQL database used to store large amounts of data without any traditional relational database table. To connect to a MongoDB database using NodeJS we use the MongoDB library "mongoose". Steps to Connect to a MongoDB Database Using NodeJSStep 1: Create a NodeJS App: First create a NodeJ
4 min read
Node.js MySQL-Create Table Using Sequelize
Introduction to Sequelize: Sequelize is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. Its features are solid transaction support, relations, eager and lazy loading, read replication and many more. Connect to MySql Database using Sequelize:Â To establish c
3 min read
MongoDB - Create Database using Mongo Shell
MongoDB is a popular NoSQL database that uses collections and documents, which are highly flexible and scalable. Unlike relational databases (RDBMS), MongoDB does not use tables and rows but stores data in a more dynamic, JSON-like format. In this article, we'll explore how to create a MongoDB datab
4 min read
How to Connect to a MySQL Database Using the mysql2 Package in Node.js?
We will explore how to connect the Node.js application to a MySQL database using the mysql2 package. MySQL can be widely used as a relational database and mysql2 provides fast, secure, and easy access to MySQL servers, it can allow you to handle database queries efficiently in Node.js applications.
6 min read
How to Connect to a MongoDB Database Using the Node.js Driver ?
MongoDB is a popular, open-source, NoSQL (non-relational) database that provides high performance, high availability, and easy scalability. Unlike traditional relational databases, MongoDB stores a JSON-like format called BSON (Binary JSON). In this article, we connect the MongoDB database to your b
4 min read
How to add table row in a table using jQuery?
In jQuery, adding a row to a table refers to dynamically inserting a new table row (<tr>) into an existing HTML table. This functionality allows developers to update and manage table content in real-time, enhancing interactivity and user experience without reloading the page. Steps to add tabl
2 min read