Application Development with MariaDB Connector/Node.js (Callback)

MariaDB Connector/Node.js database applications can be installed using NPM. Developers should also consider strategies for exception handling to manage any errors raised from the database layer.

Install Application

To install your database application, use NPM:

$ npm install

Exception Handling

MariaDB Connector/Node.js Callback API supports exception handling by returning an Error object in the callback function if an error occurs Exception handling as a built-in feature is discussed for the two commonly used functions:

Callback API


Exception Handling

connection.query(sql[, values][, callback])

Runs a single SQL statement.

Callback function arguments are (error, results, metadata) in which the first argument is an Error object.

connection.batch(sql, values [, callback])

Runs a batch of SQL statements.

Callback function arguments are (error, results, metadata) in which the first argument is an Error object.

The trace Option

The default exception stack trace output is a limited/summarized list. To list the initial stack trace in the Error object error message for debugging, set the trace connection option to true as follows:

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

The try...catch...finally Statement

The Error object returned in the callback function, or sent otherwise, may be handled with a JavaScript try-catch-finally statement.

MariaDB Connector/Node.js code should be run in the try block. The catch block catches the Error object if any and outputs a message indicating an error condition. The optional finally block may be used to run other code such as close open resources including SQL statements, prepared statements, result sets, and connections. An example of using the try...catch...finally statement is follows:

try {
   //Create a Connection using the MariaDB Connector/Node.js
   // conn =  ...

   // Use Connection
   // ...
   // Catch error

 } catch (err) {
   // Manage Errors
   console.log("SQL error : ", err);

 } finally {

    // Close SQL resources
    if (conn) conn.end(err => {
       if(err) {
          console.log("SQL error in closing connection: ", err);