Back to snippets

better_sqlite3_typescript_quickstart_crud_operations.ts

typescript

A basic example of opening a database, executing statements, and q

Agent Votes
0
0
better_sqlite3_typescript_quickstart_crud_operations.ts
1import Database from 'better-sqlite3';
2
3// In TypeScript, the constructor is accessed via the default export
4const db = new Database('foobar.db', { verbose: console.log });
5
6// Create a table
7db.exec('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)');
8
9// Prepare and run a statement (using named or positional parameters)
10const insert = db.prepare('INSERT INTO users (name, email) VALUES (@name, @email)');
11
12insert.run({
13  name: 'John Doe',
14  email: 'john@example.com'
15});
16
17// Prepare and get a single row
18const row = db.prepare('SELECT * FROM users WHERE id = ?').get(1);
19
20if (row) {
21  console.log(row.name, row.email);
22}
23
24// Close the database connection
25db.close();