Summary: In this tutorial, you will learn how to connect to an SQLite database from Bun using the bun:sqlite
module.
Introduction to bun:sqlite module
Bun offers a built-in bun:sqlite
module that natively implements SQLite3
driver. The bun:sqlite
‘s API is simple and fast.
The bun:sqlite
module includes the following features:
- Prepared statements.
- Positional and named parameters.
- Transactions.
- BLOB.
- bigint support.
- Execute multiple SQL statements in a single call.
To connect to a SQLite database, you follow these steps:
First, import the Database
class from the bun:sqlite
module:
import { Database } from "bun:sqlite";
Code language: TypeScript (typescript)
Second, create a new instance of the Database
class:
const db = new Database(dbFile);
Code language: JavaScript (javascript)
In this syntax, the dbFile
is the path to the SQLite database file you want to connect.
If the dbFile
does not exist, it will be created. Otherwise, Bun will open a new connection to the SQLite database.
Third, perform database operations such as inserting, updating, deleting, and querying data from the SQLite database.
Finally, close the database connection when it is no longer in use:
db.close()
Code language: JavaScript (javascript)
The close()
waits for the pending queries to finish before closing the database connection.
If you want to close the database connection and throw an error if there are pending queries, you can pass the true value to the close()
method:
db.close(true)
Code language: JavaScript (javascript)
Note that Bun will call the close()
method automatically when the database is garbage collected.
Connecting to SQLite example
The following example shows how to create a new Bun project and create a new SQLite database called pub:
Step 1. Open your terminal and create a new project directory
mkdir pub
cd pub
Code language: JavaScript (javascript)
Step 2. Execute the bun init
command to scaffold a minimal Bun project:
bun init
Code language: JavaScript (javascript)
It’ll prompt you to enter the package name and the entry point. Press Enter
to use the current directory as the package name and index.ts
as the entry point.
Step 3. Run the bun run
command to execute the index.ts
file:
bun run index.ts
Code language: JavaScript (javascript)
Output:
Hello via Bun!
Code language: plaintext (plaintext)
Step 4. Open the project directory and change the index.js
file to the following:
import { Database } from "bun:sqlite";
const db = new Database("pub.db");
// interact with the database
// ..
db.close();
Code language: TypeScript (typescript)
Step 5. Run the bun run
command in your terminal to create a new pub.db
database:
bun run index.js
Code language: plaintext (plaintext)
It’ll create a new SQLite named pub.db
within the project directory.
Summary
- Use the
bun:sqlite
package to interact with SQLite databases in Bun. - Create a new instance of the
Database
class to connect to a SQLite database.