Local MySQL
The Local Database module provides a simple interface for interacting with SQLite databases. It supports both in-memory and file-based databases, allowing for flexible data storage options.
Constructor
The constructor initializes a new instance of the sql
class, allowing you to specify whether to use an in-memory database or a file-based database.
constructor(location: boolean | string);
location
A boolean for an in-memory database (true
), or a string for a file-based database (specifying the database filename without the extension).
Methods
get
get
Returns the SQLite database instance.
public get get(): sqlite3.Database | null;
query
query
Executes a SQL query with optional parameters.
public query<T>(query: string, params: any[] = []): Promise<T[]>;
query
The SQL query to execute.
params
Optional parameters for the SQL query.ms
refresh
refresh
Refreshes the SQLite database connection.
public refresh(): Promise<void>;
File-Based Example
Hereās how you can use the sql
class to create a database and execute a query:
import sql from "@utils/sql";
const db = new sql("data");
try {
await db.query("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)");
await db.query("INSERT INTO users (name) VALUES (?)", ["dragos"]);
const results = await db.query("SELECT * FROM users");
console.log(results);
} catch (error) {
console.error("Database error:", error);
}
In-Memory Database Example
To create an in-memory database, simply pass true
to the constructor:
import sql from "@utils/sql";
const db = new sql(true);
try {
await db.query("CREATE TABLE IF NOT EXISTS items (id INTEGER PRIMARY KEY, value TEXT)");
await db.query("INSERT INTO items (value) VALUES (?)", ["sample"]);
const results = await db.query("SELECT * FROM items");
console.log(results);
} catch (error) {
console.error("Database error:", error);
}
Last updated