Node.js Application Connection to MySQL

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

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

Node.js MySQL environment

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

2. Access your Node.js node via SSH.

Jelastic SSH Gate

3. Once inside, get an official MySQL driver for Node.js by executing the following command:

npm install mysql

install MySQL driver for Node.js

Installation will be finished in a minute.

4. Prepare a simple script to verify 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!");
});
con.end();
The highlighted placeholders in the code above should be adjusted using the appropriate connection information (is provided within email for your MySQL container):
  • {user} - username to log into 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)

MySQL connection script

Using this script, you can check 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

run DB connection script

For successful connection a “You are connected!” phrase will be displayed in 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.