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.

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 create new file index.js.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *