MariaDB Connector/Node.js (Promise API) Examples

Example programs provided here illustrate how to use MariaDB Connector/Node.js to connect to MariaDB Enterprise and retrieve and manipulate data.

Short Example

The following example uses the Promise API to select data from the table defined in Setup for Examples. Complete information on using Connector/Node.js with Promise API is available.

const mariadb = require("mariadb");

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

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

      // Use Connection to get contacts data
      var rows = await get_contacts(conn);

      //Print list of contacts
      for (i = 0, len = rows.length; i < len; i++) {
         console.log(`${rows[i].first_name} ${rows[i].last_name} <${rows[i].email}>`);
      }
   } catch (err) {
      // Manage Errors
      console.log(err);
   } finally {
      // Close Connection
      if (conn) conn.close();
   }
}

//Get list of contacts
function get_contacts(conn) {
   return conn.query("SELECT first_name, last_name, email FROM test.contacts");
}

main();

Example output:

John Smith <john.smith@example.com>

Long Example

The following example program connects using query pipelining, and demonstrates CRUD (CREATE, READ, UPDATE, DELETE) operations within a transaction, including a batch operation, with the example setup.

const mariadb = require("mariadb");

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

   try {
      // Establish Connection (with query pipelining set)
      conn = await mariadb.createConnection({
         host: "192.0.2.50",
         user: "db_user",
         password: "db_user_password",
         database: "test",
         pipelining: true,
      });

      var contacts = [
         ["John", "Smith", "johnsmith@example.com"],
         ["Jon", "Smith", "jon.smith@example.com"],
         ["Johnny", "Smith", "johnny.smith@example.com"],
      ];

      const updateContact = {
         first_name: "John",
         email: "john.smith@example.com",
      };

      const deleteContact = {
         id: 3
      };

      await crudInPipeline(conn, contacts, updateContact, deleteContact);

   } catch (err) {
      // Manage Errors
      console.error("Error connecting to MariaDB Enterprise with pipeline: ", err);
   } finally {
      // Close Connection
      if (conn) conn.close();
   }

}

async function crudInPipeline(conn, data, update, del) {
   try {
      // Start Transaction
      await conn.beginTransaction();

      try {

         //Drop Table IF Exists
         await conn.query("DROP TABLE IF EXISTS test.contacts");

         //Create Table
         await conn.query("CREATE TABLE IF NOT EXISTS test.contacts (id INT PRIMARY KEY AUTO_INCREMENT,first_name VARCHAR(25),last_name VARCHAR(25),email VARCHAR(100)) ENGINE=InnoDB");

         // Add Contacts in Batch
         await conn.batch(
            "INSERT INTO test.contacts(first_name, last_name, email) VALUES(?, ?, ?)",
            data
         );

         // Update
         await conn.query(
            "UPDATE test.contacts SET email = ? WHERE first_name = ?",
            [update.email, update.first_name]
         );

         // Delete
         await conn.query(
            "DELETE FROM test.contacts WHERE id = ?",
            [del.id]
         );

         // Commit Changes
         await conn.commit();

         //Select data
         var rows = await conn.query("SELECT first_name, last_name, email FROM test.contacts");

         //Print list of contacts
         for (i = 0, len = rows.length; i < len; i++) {
            console.log(`${rows[i].first_name} ${rows[i].last_name} <${rows[i].email}>`);
         }

      } catch (err) {
         console.error("Error adding user, reverting changes: ", err);
         await conn.rollback();
      }
   } catch (err) {
      console.error("Error starting a transaction: ", err);
   }

   return Promise.resolve(1);
}

main();

Example output:

John Smith <john.smith@example.com>
Jon Smith <jon.smith@example.com>