Using Deno to Create and Manage SQLite Databases
Deno, a modern runtime for JavaScript and TypeScript, provides native database drivers that you can use to interact with databases like SQLite. Here's an example of how you might use Deno's SQLite database module to create, query, and manage data.
Step 1: Setting Up Deno
First, ensure you have Deno installed on your machine. You can install Deno by running:
curl -fsSL https://deno.land/install.sh | sh
Or by using package managers such as Homebrew on macOS:
brew install deno
Step 2: Create a SQLite Database Using Deno
Deno’s ecosystem includes third-party modules to interact with SQLite. One popular module is deno-sqlite
. You can use this module to create and manipulate SQLite databases.
Example Code
Here’s an example of how to use Deno's SQLite driver:
First, you need to ensure you have the necessary permissions to read and write files.
// Import the SQLite module from deno.land
import { DB } from "https://deno.land/x/sqlite/mod.ts";
// Create a new SQLite database
const db = new DB("test.db");
// Create a table
db.query(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT
)
`);
// Insert a new user into the table
db.query("INSERT INTO users (name) VALUES (?)", ["Alice"]);
// Query and log all users in the table
for (const [id, name] of db.query("SELECT id, name FROM users")) {
console.log({ id, name });
}
// Close the database connection
db.close();
Step 3: Running the Code
Save the code to a file, e.g., app.ts
, and then run it with Deno:
deno run --allow-read --allow-write app.ts
Explanation:
-
Creating and Inserting Data:
- We start by importing the
DB
class from thedeno-sqlite
module. - Then, we create a new database,
test.db
. The database file will be created in the current directory.
- We start by importing the
-
Schema Definition:
- We define a simple table
users
with two columns:id
andname
.
- We define a simple table
-
Data Insertion:
- We insert a row into the table with a single user's name, "Alice".
-
Query and Output:
- We perform a
SELECT
query to fetch all users and log theirid
andname
.
- We perform a
-
Resource Management:
- Finally, we close the database connection using
db.close()
to ensure all resources are released properly.
- Finally, we close the database connection using
By following these steps, you should be able to interact with an SQLite database within a Deno environment, benefiting from the simplicity of Deno’s architecture and the ease of TypeScript. Adjust and expand upon this basic setup to fit your application's needs.