Connecting to MySQL database
Sometimes you might need to connect to a MySQL database. There are many ways to accomplish this task and I would like to discuss one of the ways we are using here at Walden Systems, because we believe this is the most straightforward method to connect to a MySQL database.
Strategy to connecting to a MySQL database is straight forward and involves only three steps: First, we need to include the mysql module. Second, we need to create a connection using the built in mysql method, createConnection( ). Finally, we need to connect to the MySQL database using the built in mysql method, connect( ).
First, we need to include the mysql module and include it. If you don't have the mysql module installed, run the following command to install it using npm:
npm install mysql
Once the mysql module is installed, include it using the following line:
var mysql = require( 'msql' ) ;
Next, we will create the connection and connect to the MySQL database using the following code :
Create MySQL connection
var con = mysql.createConnection ( { host: "HOSTNAME", user: "USERNAME", password: "PASSWORD" } ) ;
Connect to MySQL database
con.connect ( function ( error ) { if ( error ) { throw error ; } console.log( "Connected!" ) ; } ) ;
When we put the code together, we can connect to the MySQL database:
var mysql = require( 'msql' ) ; var con = mysql.createConnection ( { host: "HOSTNAME", user: "USERNAME", password: "PASSWORD" } ) ; con.connect ( function ( error ) { if ( error ) { throw error ; } console.log( "Connected!" ) ; } ) ;