What is sqlite?
The sqlite npm package is a wrapper for SQLite, a C library that provides a lightweight, disk-based database. It doesn't require a separate server process and allows access to the database using a nonstandard variant of the SQL query language. The sqlite npm package allows you to interact with SQLite databases in a Node.js environment.
What are sqlite's main functionalities?
Create a Database
This code demonstrates how to create an in-memory SQLite database, create a table, insert data, and query the data.
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database(':memory:');
db.serialize(() => {
db.run('CREATE TABLE lorem (info TEXT)');
const stmt = db.prepare('INSERT INTO lorem VALUES (?)');
for (let i = 0; i < 10; i++) {
stmt.run('Ipsum ' + i);
}
stmt.finalize();
db.each('SELECT rowid AS id, info FROM lorem', (err, row) => {
console.log(row.id + ': ' + row.info);
});
});
db.close();
Open an Existing Database
This code demonstrates how to open an existing SQLite database file, query data from a table, and print the results.
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database('example.db');
db.serialize(() => {
db.each('SELECT rowid AS id, info FROM lorem', (err, row) => {
console.log(row.id + ': ' + row.info);
});
});
db.close();
Parameterized Queries
This code demonstrates how to use parameterized queries to prevent SQL injection attacks. It shows how to insert and query data using placeholders.
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database(':memory:');
db.serialize(() => {
db.run('CREATE TABLE lorem (info TEXT)');
const stmt = db.prepare('INSERT INTO lorem VALUES (?)');
stmt.run('Ipsum 1');
stmt.finalize();
db.get('SELECT info FROM lorem WHERE info = ?', ['Ipsum 1'], (err, row) => {
console.log(row.info);
});
});
db.close();
Other packages similar to sqlite
better-sqlite3
better-sqlite3 is a wrapper for SQLite3 that is faster and simpler to use than the sqlite package. It provides a more synchronous API, which can be easier to work with in many cases. Unlike sqlite, better-sqlite3 does not require a callback for each query, making the code more readable and easier to maintain.
sequelize
Sequelize is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite, and Microsoft SQL Server. It features solid transaction support, relations, eager and lazy loading, read replication, and more. While it supports SQLite, it is more complex and feature-rich compared to the sqlite package, making it suitable for larger applications with more complex database interactions.
knex
Knex.js is a SQL query builder for PostgreSQL, MySQL, MariaDB, SQLite3, and Oracle. It is designed to be flexible and powerful, allowing you to build complex queries with ease. Knex.js can be used as a query builder in conjunction with an ORM or as a standalone query builder. It provides a more abstracted way to interact with databases compared to the sqlite package.
SQLite Client for Node.js Apps
A wrapper library that adds ES6 promises and SQL-based migrations API to
sqlite3 (docs).
note v4 of sqlite
has breaking changes compared to v3! Please see CHANGELOG.md
for more details.
Installation
$ npm install sqlite@4.0.0-beta.2 --save
$ npm install sqlite@3 --save
Usage
This module has the same API as the original sqlite3
library (docs),
except that all its API methods return ES6 Promises and do not accept callback arguments (with the exception of each()
).
Opening the database
Without caching
import { open } from 'sqlite'
(async () => {
const db = await open({
filename: '/tmp/database.db'
})
})()
or
import { open } from 'sqlite'
open({
filename: '/tmp/database.db'
}).then((db) => {
})
With caching
If you want to enable the database object cache
import { open } from 'sqlite'
(async () => {
const db = await open({
filename: '/tmp/database.db',
cache: true
})
})()
With a custom driver
You can use an alternative library to sqlite3
as long as it conforms to the sqlite3
API.
For example, using sqlite3-offline
:
import { open } from 'sqlite'
(async () => {
const db = await open({
filename: '/tmp/database.db',
cache: true
})
})()
open
config params
const db = await open({
filename: string
mode?: OpenDatabaseEnum
driver?: any
cached?: boolean
verbose?: boolean
})
Examples
- See the
src/**/__tests__
directory for more example usages - See the
docs/
directory for full documentation. - Also visit the
sqlite3
library API docs
Creating a table and inserting data
await db.exec('CREATE TABLE tbl (col TEXT)')
await db.exec('INSERT INTO tbl VALUES ("test")')
Getting a single row
const result = await db.get('SELECT col FROM tbl WHERE col = ?', 'test')
const result = await db.get('SELECT col FROM tbl WHERE col = ?', ['test'])
const result = await db.get('SELECT col FROM tbl WHERE col = :test', {
':test': 'test'
})
Getting many rows
const result = await db.all('SELECT col FROM tbl')
Inserting rows (part 2)
const result = await db.run(
'INSERT INTO tbl (col) VALUES (?)',
'foo'
)
const result = await db.run('INSERT INTO tbl(col) VALUES (:col)', {
':col': 'something'
})
Updating rows
const result = await db.run(
'UPDATE tbl SET col = ? WHERE col = ?',
'foo',
'test'
)
Prepared statement
const stmt = await db.prepare('SELECT col FROM tbl WHERE 1 = ? AND 5 = ?5')
await stmt.bind({ 1: 1, 5: 5 })
let result = await stmt.get()
const stmt = await db.prepare(
'SELECT col FROM tbl WHERE 13 = @thirteen ORDER BY col DESC'
)
const result = await stmt.all({ '@thirteen': 13 })
Get the driver instance
Useful if you need to call methods that are not supported yet.
const rawDb = db.getDatabaseInstance()
const rawStatement = stmt.getStatementInstance()
Closing the database
await db.close()
ES6 tagged template strings
This module is compatible with sql-template-strings.
import SQL from 'sql-template-strings'
const book = 'harry potter';
const author = 'J. K. Rowling';
const data = await db.all(SQL`SELECT author FROM books WHERE name = ${book} AND author = ${author}`);
Migrations
This module comes with a lightweight migrations API that works with SQL-based migration files
With default configuration, you can create a migrations/
directory in your project with SQL files,
and call the migrate()
method to run the SQL in the directory against the database.
See this project's migrations/
folder for examples.
await db.migrate({
force?: boolean
table?: string
migrationsPath?: string
})
API Documentation
See the docs
directory for full documentation.
References
Support
- Join #node-sqlite chat room on Gitter to stay up to date regarding the project
- Join #sqlite IRC chat room on Freenode about general discussion about SQLite
License
The MIT License © 2020-present Kriasoft / Theo Gravity. All rights reserved.
Made with ♥ by Konstantin Tarkus (@koistya), Theo Gravity and contributors