Monday 20 February 2017

Connecting Mysql with Node.js

We know  that NodeJS is becoming popular due to its fast prototype development and implemention with more performance than Python or any other programming language.
Lets start by creating a package.json file.

To create package.json file . Goto directory where you want to setup files,then run command
npm init.
Make sure that you have installed version of Node and NPM.

Now lets install mysql.
You can run 
                  npm install mysql

//create a file named database.js for database related options

const mysql = require('mysql'); //export required module

//create connection object 
const connection = mysql.createConnection({
    'host': 'localhost',
    'port': 3306,
    'user': 'username',
    'password': 'password',
    'database': 'databasename'
});

//test connection 
connection.connect(function(error) {
    if (error) {
        console.log('error code is ' + error.code);
    } else {
        console.log('connection successfull');
    }
});

//check for error in connection
connection.on('error', (error) => {
    console.log(`error code is ${error.code}`);
});

//export the module to use with other files
module.exports = connection;  



Now enter touch index.js to create a new file.

open index.js in editor and write

const connection = require('./database.js');
//make a query
connection.query('show databases, (error, result) => {
    if (error) {
        console.log('error in processing query');
    } else {
        console.log(JSON.stringify(result));
    }
});


Thanks for reading.Please Mention your comment if you have any questions regarding this.


No comments:

Post a Comment