Setting Node.js MySQL Connection
We can create applications with databases using Node.js. In this tutorial, we will create a node application connected with the MySQL database. MySQL is a very popular RDBMS. To create this application we need to,
- Install MySQL
- Install MySQL driver
- Create a connection
- Execute and test
Install MySQL
To install the MySQL database, we first need to download the database from https://www.mysql.com/downloads/ and then install it to your machine,
Install MySQL driver
Once MySQL database is up and running, then we need to install MySQL driver by using npm. We need to “mysql” module in our application to access the database. This driver will provide a layer to access the database programmatically.
C:\Users\me>npm
install mysql
Upon the successful completion of the installation, you will be able to see something like
Now, we can access and manipulate the database with this database driver. This module can be used as,
var mysql = require('mysql');
Create a Connection
Create a .js file and place the code in this file (Let the name of the file be con.js)
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "username",// replace with username
password: "password" // replace with password
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
Execute and test
The result will be
C:\Users\me\Desktop\brackets>node con.js
Connected!
Connected!