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
connectEstablishes a connection to the database using provided options or environment variables.
end
endForcefully closes the database connection.
query
queryExecutes a SQL query on the database and returns the result.
sql
The SQL query string.
connected
Optional array of values to be replaced in the query.
connection
connectionReturns the database connection handle.
quit
quitSafely closes the database connection.
Example
Here’s how you can use the DBClass to connect to a database and execute a query:
This example demonstrates how to create a new database connection, execute a query to retrieve all users from the users table.
Last updated