Connector/Node.js Guide
Quickstart guide for MariaDB Connector/Node.js
Quickstart Guide: MariaDB Connector/Node.js
MariaDB Connector/Node.js is a client library that enables Node.js applications to connect and interact with MariaDB and MySQL databases. It's built natively in JavaScript and supports both Promise and Callback APIs, with the Promise API being the default and recommended approach. It is licensed under the LGPL.
1. Installation
The easiest way to install MariaDB Connector/Node.js is using npm (Node Package Manager):
npm install mariadb2. Basic Usage (Promise API - Recommended)
The Promise API simplifies asynchronous operations with async/await. For optimal performance and resource management, it's recommended to use a connection pool.
a. Create a Connection Pool:
const mariadb = require('mariadb');
const pool = mariadb.createPool({
host: 'localhost',
port: 3306,
user: 'your_username',
password: 'your_password',
database: 'your_database_name',
connectionLimit: 5 // Adjust as needed
});
console.log("Connection pool created.");Replace localhost, 3306, your_username, your_password, and your_database_name with your actual database details.
b. Perform Database Operations:
Here's an async function example to get a connection, execute queries, and release the connection back to the pool.
3. Basic Usage (Callback API - for Compatibility)
If you need compatibility with older Node.js database drivers (mysql, mysql2), you can use the Callback API.
Important Notes:
Error Handling: Always include robust error handling (
try...catchfor Promises,if (err)for Callbacks) in your database interactions.Parameterized Queries: Always use parameterized queries (e.g.,
WHERE status = ?,VALUES (?, ?)) to prevent SQL injection attacks.Connection Pooling: For production applications, always use a connection pool (
mariadb.createPool()) instead of single connections to manage resources efficiently.conn.release()vs.conn.end(): When using a pool, useconn.release()to return the connection to the pool. Useconn.end()orpool.end()only when gracefully shutting down your application.
Further Resources:
Last updated
Was this helpful?

