Connect with MariaDB Connector/Node.js (Callback API)
This page is part of MariaDB's Documentation.
The parent of this page is: MariaDB Connector/Node.js with Callback API
Topics on this page:
Overview
Node.js developers can use MariaDB Connector/Node.js to establish client connections with MariaDB database products.
Require Callback API
MariaDB Connector/Node.js provides two different connection implementations: one built on the Promise API and the other built on the Callback API.
To use the Callback API, use the following module:
const mariadb = require('mariadb/callback');
Connect
createConnection(options) -> Connection
is the base function used to create a Connection
object.
The createConnection(options)
function returns a Connection
object.
The commonly used options in createConnection(options)
are listed in this table:
Option | Description |
---|---|
| Database name to establish a connection to. No default is configured. |
| Connection timeout in milliseconds. In Connector/Node.js 2.5.6, the default value changed to 1000. The default value for earlier versions is 10000. |
| A boolean value to indicate whether to return result sets as array instead of the default JSON. Arrays are comparatively faster. |
Code Example: Connect
The following code example connects using the database and user account created in the example setup:
const mariadb = require('mariadb/callback');
// Declare async function
function main() {
let conn;
try {
conn = mariadb.createConnection({
host: "192.0.2.50",
user: "db_user",
password: "db_user_password",
database: "test",
});
// Use Connection
// ...
} catch (err) {
// Manage Errors
console.log("SQL error in establishing a connection: ", err);
} finally {
// Close Connection
if (conn) conn.end(err => {if(err){
console.log("SQL error in closing a connection: ", err);}
});
}
}
main();
A
try...catch...finally
statement is used for exception handling.New connections are created in auto-commit mode by default.
When you are done with a connection, close it to free resources. Close the connection using the
connection.end([callback])
function.The script calls the
connection.end([callback])
function to close/end the connection in thefinally
block after the queries that are running have completed.The
end()
function takes a callback function that defines one implicit argument for theError
object if thrown in closing the connection as argument. If no error is generated in closing a connection theError
object isnull
.