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).

1
2
3
4
5
6
7
8
9
10
11
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 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.

  • 0 Users Found This Useful
Was this answer helpful?

Related Articles

Deploy Node.js Project > via Archive / URL

Upload and Deploy Your Node.js Application With Cloudjiffy you can easily upload and deploy...

Deploy Node.js Project > via GIT/SVN

Deploy Node.js Project via GIT/SVN With Cloudjiffyyou can host any public or your private...

PHP Accelerators

  PHP accelerators   A PHP accelerator is a PHP extension designed to improve the performance...

MongoDB - Node.js Connection

Node.js Application Connection to MongoDB MongoDB is a popular NoSQL databases, which is...

Powered by WHMCompleteSolution