MySql/MariaDB - Node.js Connection

Node.js Application Connection to MySQL

MySQL is one of the most popular open-source SQL database, used by the world’s largest organizations. In this guide, we’ll overview a simple example of Node.js application connection to a MySQL server.

1. To establish a connection, you’ll need the Node.js and MySQL servers. You can either create them at Cloudjiffy or use external hosts.


For this tutorial, we’ll use a single environment with both instances inside.

2. Access your Node.js node via SSH.


3. Once inside, get an official MySQL driver for Node.js then prepares a simple script to verify the connection.
Create a file with the .js extension, using any text editor of your choice can (e.g. vim script.js).

var mysql = require('mysql');
var con = mysql.createConnection({
 host: "{host}",
 user: "{user}",
 password: "{password}",
 database: "{database}"
con.connect(function(err) {
 if (err) throw err; console.log("You are connected!");
The highlighted placeholders in the code above should be adjusted using the appropriate connection information (is provided within the email for your MySQL container):  
  • {user} - username to log into the database with
  • {password} - password for the appropriate user
  • {host} - link to your MySQL container
  • {database} - database to be accessed (e.g. the default one - MySQL)                                               


Using this script, you can check the connection to the database from your application server and, if it fails, get an error description.

5. Run code with the appropriate command:

node script.js


For successful connection a “You are connected!” phrase will be displayed in the terminal, otherwise, error description will be provided. Now, when you are sure your database container is accessible, extend code to execute some real actions on your DB server.

Was this answer helpful? 1 Users Found This Useful (1 Votes)