Batch Operations with MariaDB Connector/Node.js (Promise API)

Node.js developers can connect to MariaDB Enterprise using MariaDB Connector/Node.js to perform batch operations with the Promise API. Promise API is the default API.

Batch Operations

The connection.batch(sql, values) Promise function is used to run a batch of SQL statements. The function parameters are discussed in following table:





string or JSON

The SQL string or JSON object for the SQL statement to run, and optionally, connection options that will supersede the default options. If a JSON object is supplied it must include a property called sql for the SQL statement to run.


array or object

Placeholder values.

The connection.batch() function returns a Promise object that resolves with a JSON object if no error occurs, and rejects with an Error object if an error condition occurs.

Code Example: Batching DML

The following batch DML (Data Manipulation Language) example shows how to use a batch operation to add multiple contacts' details to the example table:

const mariadb = require("mariadb");

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

   try {
      conn = await mariadb.createConnection({
         user: "db_user",
         host: "",
         password: "db_user_password",
         database: "test",

      //Declare a JSON array for data to add
      var contacts = [
         ["John", "Smith", ""],
         ["Jon", "Smith", ""],
         ["Johnny", "Smith", ""],

      // Use Connection to Add Contacts in Batch
      await add_contacts(conn, contacts);

   } catch (err) {
       // Manage Errors
   } finally {
       // Close Connection
       if (conn) conn.close();

async  function add_contacts(conn, data) {
   return conn.batch(
      "INSERT INTO test.contacts(first_name, last_name, email) VALUES (?, ?, ?)",

  • MariaDB Connector/Node.js adds data to the database with INSERT statement.

  • Add an async function add_contacts(conn, data) for adding a batch of data.

  • The async keyword declares the function to be an asynchronous function.

  • The add_contacts() function should return a Promise object because it is an async function.

  • Declare a variable contacts for defining a JSON object that represents multiple contacts.

  • The batch() function sends a query to the database and returns the result as a Promise.

Confirm that the data was properly added by using MariaDB Client to execute a SELECT statement:

SELECT * from test.contacts;

Example output:

| id | first_name | last_name | email                  |
|  1 | John       | Smith     | |
|  2 | Jon        | Smith     |  |
|  3 | Johnny     | Smith     ||