Remote MySQL
The Database module provides a simple interface for connecting to a MySQL database using the mysql2/promise library. It manages connection states and offers methods for executing safe queries
States
The DBStates
enum defines the various states of the database connection:
connecting
The connection is in the process of being established.
connected
The connection has been successfully established.
error
An error occurred during the connection or query execution.
closed
The connection has been closed.
Options
The DBOptions
interface allows you to specify optional parameters for the database connection:
interface DBOptions {
host?: string; // Database host (default: process.env.DB_HOST)
user?: string; // Database user (default: process.env.DB_USER)
password?: string; // Database password (default: process.env.DB_PASSWORD)
database?: string; // Database name (default: process.env.DB_NAME)
port?: number; // Database port (default: process.env.DB_PORT)
alias?: string; // Optional alias for the connection
}
Methods
connect
connect
Establishes a connection to the database using provided options or environment variables.
private async connect(): Promise<void>;
end
end
Forcefully closes the database connection.
public async end(): Promise<void>;
query
query
Executes a SQL query on the database and returns the result.
public async query<T>(sql: string, values?: any[]): Promise<T[]>;
sql
The SQL query string.
connected
Optional array of values to be replaced in the query.
connection
connection
Returns the database connection handle.
get connection(): Connection | null;
quit
quit
Safely closes the database connection.
private async quit(): Promise<void>;
Example
Here’s how you can use the DBClass
to connect to a database and execute a query:
import DB, { DBOptions } from "@utils/db";
const options: DBOptions = {
host: "localhost",
user: "root",
password: "password",
database: "database",
port: 3306,
};
const db = new DB(options);
try {
const results = await db.query<any>("SELECT * FROM users");
console.log(results);
} catch (error) {
console.error("Database error:", error);
}
This example demonstrates how to create a new database connection, execute a query to retrieve all users from the users
table.
Last updated