Connect with MariaDB Connector/Node.js (Promise API)

Overview

Node.js developers can use MariaDB Connector/Node.js to establish client connections with MariaDB database products.

Require Promise API

MariaDB Connector/Node.js provides two different connection implementations: one built on the Promise API and the other built on the Callback API. Promise is the default.

To use the Promise API, use the mariadb module:

const mariadb = require('mariadb');

Connect

createConnection(options) -> Promise is the base function used to create a Connection object.

The createConnection(options) returns a Promise that resolves to a Connection object if no error occurs, and rejects with an Error object if an error occurs.

The commonly used options in createConnection(options) are listed in this table:

Determine the connection information for your MariaDB SkySQL database service:

Option

Description

host

IP address or DNS of the database server. Default is localhost.The fully Qualified Domain Name in the Service Details view

port

Port # to connect database at. Default is 3306.The Read-Write Port or Read-Only Port in the Service Details view

user

User name to connect with databaseThe desired username, which might be the default username in the Service Credentials view

password

User passwordThe user's password, which might be the default password in the Service Credentials view if it was not yet customized

ssl.ca

The contents of the skysql_chain.pem file containing the "Certificate Authority Chain"

database

Database name to establish a connection to. No default is configured.

connectTimeout

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.

rowsAsArray

A boolean value to indicate whether to return result sets as array instead of the default JSON. Arrays are comparatively faster.

Create a file named .env to store your database credentials:

MDB_HOST = 192.0.2.50
MDB_PORT = 3306
MDB_USER = db_user
MDB_PASS = db_user_password
MDB_HOST = 192.0.2.50
MDB_PORT = 3306
MDB_USER = db_user
MDB_PASS = db_user_password
MDB_HOST = example.skysql.net
MDB_PORT = 5001
MDB_CA_PEM = /path/to/skysql_chain.pem
MDB_USER = db_user
MDB_PASS = db_user_password

Code Example: Connect

The following code example connects to a server at the IP address 192.0.2.50 using the database and user account created in Setup for Examples:

// Required Modules
const fs = require("fs");
const mariadb = require("mariadb");
require("dotenv").config()

// Declare async function
async function main() {
   let conn;

   try {
      conn = await mariadb.createConnection({
         host: process.env.MDB_HOST,
         port: process.env.MDB_PORT,
         user: process.env.MDB_USER,
         password: process.env.MDB_PASS,
         database: "test",
      });

      // Use Connection
      // ...
   } catch (err) {
      // Manage Errors
      console.log("SQL error in establishing a connection: ", err);
   } finally {
      // Close Connection
      if (conn) conn.close();
   }
}

main();
// Required Modules
const fs = require("fs");
const mariadb = require("mariadb");
require("dotenv").config()

// Certificate Authority (CA)
const serverCert = [fs.readFileSync(process.env.MDB_CA_PEM, "utf8")];

// Declare async function
async function main() {
   let conn;

   try {
      conn = await mariadb.createConnection({
         host: process.env.MDB_HOST,
         port: process.env.MDB_PORT,
         user: process.env.MDB_USER,
         password: process.env.MDB_PASS,
         ssl: { ca: serverCert },
         database: "test",
      });

      // Use Connection
      // ...
   } catch (err) {
      // Manage Errors
      console.log("SQL error in establishing a connection: ", err);
   } finally {
      // Close Connection
      if (conn) conn.close();
   }
}

main();
  • Load the mariadb module using the require() function.

  • Declare an async function called main() using the async keyword.

  • An async function provides asynchronous, Promise-based code behavior.

  • Async functions may declare await expressions using the await keyword.

  • Await expressions yield control to a promise-based asynchronous operation.

  • Await expressions resume control after the awaited operation is either fulfilled or rejected.

  • The return value of an await expression is the resolved value of the Promise.

  • The async function name main is arbitrary and does not have special meaning as in some other programming languages.

  • Declare a variable called conn for the connection to be created using a let statement with the async function main.

  • A try...catch...finally statement is used for exception handling.

  • New connections are by default created in auto-commit mode.

  • In the try block, create a new connection using the mariadb#createConnection(options) function in the Promise API.

  • Send error messages if any to the console in the catch block.

  • When you are done with a connection, close it to free resources. Close the connection using the close() function.