MegaORM MySQL
This package provides a simple, high-level, unified API for interacting with MySQL databases. It simplifies creating connections, executing queries, and managing transactions.
While this package is designed for MegaORM, you are free to use it independently in any project as needed.
Table of Contents
Installation
To install this package, run the following command:
npm install @megaorm/mysql
Features
- Easy connection setup with MySQL databases
- Support for parameterized queries to prevent SQL injection
- Built-in transaction management
- Simple, high-level, unified API for all MegaORM drivers
- Typescript support
Create Connection
To start interacting with your MySQL database, you need to create a connection.
- First, import
MySQL
driver from @megaorm/mysql
to use it in your project.
const { MySQL } = require('@megaorm/mysql');
- Next, create an instance of
MySQL
and provide the necessary database configuration.
const driver = new MySQL({
database: 'test',
user: 'root',
password: 'root',
host: 'localhost',
});
- Finally, use the
create()
method to establish a connection to the database.
driver
.create()
.then((r) => console.log(r))
.catch((e) => console.log(e));
Throws a CreateConnectionError
if there was an issue creating the connection.
Execute Queries
Once you’ve established a connection, you can start executing SQL queries on your MySQL database.
- For select queries, the result is an array of objects representing the rows from the query. Each object corresponds to a row, with the column names as keys.
connection
.query('SELECT * FROM users;')
.then((result) => console.log(result))
.catch((error) => console.log(error));
- For inserting a single row, the result will contain the inserted row’s ID. This ID is the auto-incremented value for the primary key, for example.
const data = ['user1@gmail.com', 'pass1'];
connection
.query('INSERT INTO users (email, password) VALUES (?, ?);', data)
.then((result) => console.log(result))
.catch((error) => console.log(error));
- When inserting multiple rows, the result will typically be undefined because no specific data is returned for bulk inserts.
const data = ['user2@gmail.com', 'pass2', 'user3@gmail.com', 'pass3'];
connection
.query('INSERT INTO users (email, password) VALUES (?, ?), (?, ?);', data)
.then((result) => console.log(result))
.catch((error) => console.log(error));
- For updates, the result will generally be undefined when the operation is successful.
const data = ['updated_email@example.com', 22];
connection
.query('UPDATE users SET email = ? WHERE id = ?;', data)
.then((result) => console.log(result))
.catch((error) => console.log(error));
- Similar to the update query, the result will be undefined after a successful delete operation. You won’t receive any data back.
const data = [33];
connection
.query('DELETE FROM users WHERE id = ?;', data)
.then((result) => console.log(result))
.catch((error) => console.log(error));
For queries like CREATE TABLE
or DROP TABLE
, the result will be undefined
, since no specific data is returned.
Close Connection
Always close the connection after you're done using it. This is important because it frees up resources and prevents problems like memory leaks.
connection
.close()
.then((r) => console.log(r))
.catch((e) => console.log(e));
Throws a CloseConnectionError
if there was an issue closing the connection.
Transactions
A transaction ensures that a group of database operations is treated as a single unit. Either all operations succeed (commit), or none of them are applied (rollback). This helps maintain data integrity.
await connection.beginTransaction();
try {
const userId = await connection.query(
'INSERT INTO users (email, password) VALUES (?, ?)',
['john@example.com', 'password']
);
await connection.query(
'INSERT INTO profiles (user_id, city, age) VALUES (?, ?, ?)',
[userId, 'Tokyo', 30]
);
await connection.commit();
} catch (error) {
await connection.rollback();
}
beginTransaction()
: Throws BeginTransactionError
if there was an issue
commit()
: Throws CommitTransactionError
if there was an issue
rollback()
: Throws RollbackTransactionError
if there was an issue.
Usage Example
In this example, we’ll walk through the process of creating a connection to your MySQL
database, executing a query to fetch data from a table, and then closing the connection once you’re done. This example uses an async function to handle the asynchronous operations.
const { MySQL } = require('@megaorm/mysql');
const app = async () => {
const driver = new MySQL({
database: 'test',
user: 'root',
password: 'root',
host: 'localhost',
});
const connection = await driver.create();
const users = await connection.query('SELECT * FROM users');
console.log(users);
await connection.close();
};
app();
Driver Options
These options allow you to customize your MySQL connection according to your specific requirements, including multi-factor authentication, SSL configuration, and advanced connection settings.