Summary: in this tutorial, you will learn how to create new tables in SQLite from Node.js apps.
This tutorial begins where the “Connecting to SQLite Databases from Node.js” tutorial left off.
Creating a table from the Node.js app #
To create a new table in an SQLite database from a Node.js app, you follow these steps:
First, import sqlite3 from sqlite3 module:
import sqlite3 from "sqlite3";
Second, open a new database connection to the SQLite database:
const db = new sqlite3.Database("my.db");
Third, call the exec() method of the Database object to execute a CREATE TABLE statement to create a table:
db.exec(sql, (err) => {
// handle error here
});
Finally, close the database connection:
db.close()
Since the exec() method uses the traditional callback style which is quite challenging to work with. To make it easier, we can define a function execute() that wraps the exec() method and returns a Promise:
const execute = async (db, sql) => {
return new Promise((resolve, reject) => {
db.exec(sql, (err) => {
if (err) reject(err);
resolve();
});
});
};
And we can use the execute() function using async/await syntax:
try {
await execute(sql);
} catch(error) {
console.log(error);
}
Modifying the Node.js app #
Step 1. Create sql.js and export the execute function:
export const execute = async (db, sql) => {
return new Promise((resolve, reject) => {
db.exec(sql, (err) => {
if (err) reject(err);
resolve();
});
});
};
Step 2. Add the createTable.js to the project:
import sqlite3 from "sqlite3";
import { execute } from "./sql.js";
const main = async () => {
const db = new sqlite3.Database("my.db");
try {
await execute(
db,
`CREATE TABLE IF NOT EXISTS products (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
price DECIMAL(10, 2) NOT NULL)`
);
} catch (error) {
console.log(error);
} finally {
db.close();
}
};
main();
Step 3. Open the terminal and run the app:
npm start
Step 4. Verify the table creation.
First, open a new terminal and use the sqlite3 tool to connect to the my.db database:
sqlite3 my.db
Second, list all the tables in the my.db database:
.tables
Output:
products
The output indicates that the products table was created.
Third, examine the structure of the products table:
.schema products
Output:
CREATE TABLE products (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
price DECIMAL(10, 2) NOT NULL
);
Finally, quit the sqlite3 tool:
.quit
Summary #
- Use the
exec()method of theDatabaseobject to execute aCREATE TABLEstatement and create a new table in an SQLite database from Node.js.
Thank you for your feedback!