Connecting to MySQL database

walden systems, javascript, mysql, connect, createconnection, npm
a high-level, interpreted programming language that conforms to the ECMAScript specification. It is a language that is also characterized as dynamic, weakly typed, prototype-based and multi-paradigm. Alongside HTML and CSS, JavaScript is one of the three core technologies of the World Wide Web.[9] JavaScript enables interactive web pages and thus is an essential part of web applications. The vast majority of websites use it,[10] and all major web browsers have a dedicated JavaScript engine to execute it.

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!" ) ;
         }
    ) ;