Node.js Code Walkthrough

Overview

This walkthrough explains how to perform a simple test of a SkySQL service using Node.js code, as described in our Quickstart experience.

Done with this walkthrough? Return to Step 3 of the Quickstart

Dependency

  • Node.js 12, 14, 16

Install MariaDB Connector/Node.js via npm

Install MariaDB Connector/Node.js via npm. Initialize a new Node.js project in an empty directory and install MariaDB Connector/Node.js:

$ npm init --yes

$ npm install mariadb

Prepare Code

Using your editor of choice, create a file named app.js

Connect

Copy the following code into app.js with the following modifications:

  • Change the host, user, and password for your service

  • Set the ssl_ca path to the full path where you saved the SkySQL certificate authority chain file.

const mariadb = require("mariadb");
const fs = require("fs");

async function main() {
    const serverCert = fs.readFileSync("/path/to/skysql_chain.pem", "utf8");

    let connection;
    try {
        connection = await mariadb.createConnection({
            host: "quickstart.mdbxxxxxxx.db.skysql.net",
            port: 5046,
            ssl: { ca: serverCert },
            user: "DBXXXXXXXX",
            password: "xxxxxxxxxx",
        });

        // If this doesn't work with your DB, try using utf8mb4 instead:
        await connection.execute("SET NAMES utf8");

        // Start of code that uses the connection

        // End of code that uses the connection
    } catch (err) {
        console.log(err);
    } finally {
        if (connection) await connection.close();
    }
}

main();

Prepare the Table

The following code should be placed after // Start of code that uses the connection:

await connection.execute("CREATE DATABASE IF NOT EXISTS quickstart");
await connection.execute("USE quickstart");

await connection.execute(
    "CREATE TABLE programming_language ("
   +"  name VARCHAR(50) NOT NULL UNIQUE,"
   +"  rating INT"
   +")");

Data In

To demonstrate adding data to the database, we will use execute to insert one row at a time, or the batch method to insert multiple rows.

The following code should be placed before // End of code that uses the connection:

// Insert a single row using execute:
await connection.execute(
    "INSERT INTO programming_language VALUES (?, ?)",
    ["JavaScript", 10]
);

// Insert multiple rows using batch and an array of row values:
await connection.batch(
    "INSERT INTO programming_language VALUES (?, ?)", [
         ["Java", 9],
         ["Python", 8],
         ["C++", 7],
         ["C#", 6],
         ["Go", 5],
         ["Rust", 4],
         ["PHP", 3],
    ]);

Data Out

To demonstrate retrieving data, we will use the query method.

The following code should be placed before // End of code that uses the connection:

let rows = await connection.query(
    "SELECT name, rating FROM programming_language ORDER BY rating DESC"
);
rows.forEach(row => {
    console.log(`${row.rating} - ${row.name}`);
});

console.log('---');
console.log(`Got ${rows.length} rows`);
console.log('---');
console.log(`Type of name field: ${typeof(rows[0].name)}`);
console.log(`Type of rating field: ${typeof(rows[0].rating)}`);

Run the Test

Start the application by running the following command (or equivalent option in your IDE):

$ node app

You should see the following output:

10 - Python
9 - Java
8 - C++
7 - JavaScript
6 - C#
5 - Go
4 - Rust
3 - PHP
---
Got 8 rows
---
Type of name field: string
Type of rating field: number

Done with this walkthrough? Return to Step 3 of the Quickstart