Node.js is very popular in Todays for make chat system, real-time notification, real-time developing etc.
So, Today, I am going to give you very simple example of How to use MySQL Query in Node JS. If you use node.js then you can see how it is work and there are several driver for different task like redis, socket io, express etc.
But Node.js have a driver for MySQL that way we can easily connect with database and you can use select, insert, update and delete sql query.
So, in this example i going to give from scratch so if you are beginner and you haven't installed nodejs on your server then fire bellow command:
sudo apt-get update
sudo apt-get install nodejs
Ok, now we have to also need to install npm because we will install mysql package using npm command, so if you not installed this command before then install by following command.
sudo apt-get install npm
Ok, now we are ready for install mysql node.js driver by following command:
sudo npm install mysql
Now, I am going to give you very basic example, so first you have a one database "test" and inside that database you have "users" table.
Ok, so create new file server.js and put bellow code inside that file:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'root',
database : 'test'
});
connection.connect();
connection.query('SELECT * FROM users', function(err, result, fields) {
if (err) throw err;
console.log(result);
});
connection.end();
Now you have to run this file by following command:
nodejs server
Thanks