Node.
js MySQL Tutorial
[Link]/nodejs-mysql-tutorial
[Link] and MySQL are one of the necessary binding needed for any web application.
MySQL is one of the most popular open-source databases in the world and efficient as
well. Almost every popular programming language like Java and PHP rovides driver to
access and perform operations with MySQL.
In this Node js and MySQL tutorial, we are going how to bind Node js with MySQL
database. We will learn how to connect [Link] server with MySQL, pool connections to
improve performance, query the tables, and call stored procedures.
To be able to follow up with the code examples in this [Link] and MySQL tutorial, you
should have MySQL installed on your computer.
You can download a free MySQL database at [Link]
Quick Start: How to Use MySQL in Node
Assuming you have Node and MySQL installed on your computer. Let’s quicky use
MySQL in Node in three easy steps:
Step 1: Create a new [Link] project
Create a new directory and initialize a Node project using the NPM.
$ mkdir mysqlexperiment && cd mysqlexperiment
$ npm init --y
Step 2: Install mysql node module
Install the mysql node module using the NPM.
npm install --save mysql
Step 3: Connect with MySQL
Create an [Link] file and copy/paste the code shown below. Change the MySQL
credentials accordingly with your system.
const mysql = require('mysql');
const connection = [Link]({
host:'localhost',
user:'user',
1/10
password:'password',
database:'databasename'
});
[Link]((err) => {
if (err) throw err;
[Link]('Connected to MySQL Server!');
});
Run the code using the following command.
node [Link]
Observe the ‘Connected to MySQL Server!’ message in the terminal.
If you have the latest MySQL server installed, you might end up getting an error saying
the following.
{
code: 'ER_NOT_SUPPORTED_AUTH_MODE',
errno: 1251,
sqlMessage: 'Client does not support authentication protocol requested by server;
consider upgrading MySQL client',
sqlState: '08004',
fatal: true
}
To tackle this issue, create a new user in your MySQL server with
‘mysql_native_password’ authentication mechanisum.
Here is how you can do it quickly. First, log in to MySQL server using root access.
mysql -u root -p
Then run these commands one by one.
CREATE USER 'newuser'@'localhost' IDENTIFIED WITH 'mysql_native_password' BY
'newpassword';
GRANT ALL PRIVILEGES ON * . * TO 'newuser'@'localhost';
FLUSH PRIVILEGES;
In the code, pass the new credentials to connect to the MySQL server. Let’s proceed
further.
Pooling MySQL Connections
The code shown earlier is not meant for a production use. It’s merely to get you started
with Node and MySQL. In a production scenario, we must use connection pooling to
improve performance of MySQL and not overload the MySQL server with too many
connections.
2/10
Let’s explain it with a simple example.
Consider the code shown below.
const express = require("express");
const app = express();
const mysql = require('mysql');
const connection = [Link]({
host :'localhost',
user :'username',
password :'password',
database :'databasename'
});
[Link]((err)=>{
if(err)throw err;
[Link]('Connected to MySQL Server!');
});
[Link]("/",(req,res)=>{
[Link]('SELECT * from users LIMIT 1',(err, rows)=>{
if(err)throw err;
console. log('The data from users table are: \n', rows);
[Link]();
});
});
[Link](3000, () => {
[Link]('Server is running at port 3000' );
});
We are integrating express module to create a web server. Install the module using the
following command.
npm install --save express
We are creating a MySQL connection on every request coming from the user. Soon after
getting multiple concurrent requests, MySQL server will get overloaded and throw an
error.
To simulate the concurrent connection scenario, we are going to use a tool called siege.
Use this command to install it in Ubuntu system.
sudo apt-get install siege
Run our Node server.
3/10
node [Link]
Let’s simulate the concurrent requests.
siege -c10 -t1M [Link]
Assuming you are running the Node server on Port 3000.
Here is the output.
As you can see the output above, our server crashed while handling concurrent requests.
To tackle this scenario, we use Pooling mechanism.
Connection Pooling is a mechanism to maintain a cache of database connection so that
connection can be reused after releasing it.
Let’s rewrite our code to support connection pooling.
const express = require("express");
const app = express();
const mysql = require('mysql');
const pool = [Link]({
host :'localhost',
user :'username',
password :'password',
database :'databasename'
});
[Link]("/",(req,res)=>{
[Link]((err, connection)=>{
if(err)throw err;
console. log('connected as id '+ [Link]);
[Link]('SELECT * from users LIMIT 1',(err, rows)=>{
[Link]();// return the connection to pool
if(err)throw err;
console. log('The data from users table are: \n', rows);
});
});
});
[Link](3000, () => {
[Link]('Server is running at port 3000' );
});
Run the app using the following command.
node [Link]
4/10
Lets fire up 10 concurrent users for 1 minute using siege by using this command.
siege -c10 -t1M [Link]
Here is the output.
Our server is effectively handling the multiple requests with ease. I have used this
approach in multiple production software solutions with heavy payload and it works like
charm.
Let’s learn how to execute various MySQL queries using Node.
Executing Queries
Let’s learn how to execute queries using [Link].
Inserting Rows into Table
Here is the code to add new rows in the table.
const mysql = require('mysql');
const pool = [Link]({
connectionLimit :100,//important
host :'localhost',
user :'root',
password :'',
database :'todolist',
debug :false
});
// add rows in the table
function addRow(data){
let insertQuery ='INSERT INTO ?? (??,??) VALUES (?,?)';
let query = [Link](insertQuery,["todo","user","notes",[Link],[Link]]);
[Link](query,(err, response)=>{
if(err){
console. error(err);
return;
}
// rows added
console. log([Link]);
});
}
5/10
// timeout just to avoid firing query before connection happens
setTimeout(() => {
// call the function
addRow({
"user": "Shahid",
"value": "Just adding a note"
});
},5000);
The [Link] function will perform the query escape.
Querying data in Table
Here is the code to query rows in the table.
const mysql = require('mysql');
const pool = [Link]({
connectionLimit :100,//important
host :'localhost',
user :'root',
password :'',
database :'todolist',
debug :false
});
// query rows in the table
function queryRow(userName){
let selectQuery ='SELECT * FROM ?? WHERE ?? = ?';
let query = [Link](selectQuery,["todo","user", userName]);
// query = SELECT * FROM `todo` where `user` = 'shahid'
[Link](query,(err, data)=>{
if(err){
console. error(err);
return;
}
// rows fetch
console. log(data);
});
}
6/10
// timeout just to avoid firing query before connection happens
setTimeout(() => {
// call the function
// select rows
queryRow('shahid');
},5000);
If you would like to add multiple rows in the single query, you can pass an array in the
values. Like this.
let insertQuery = 'INSERT INTO ?? (??,??) VALUES (?,?)';
let values = [["shahid","hello"],["Rohit","Hi"]]; // each array is one row
let query = [Link](insertQuery,["todo","user","notes",values]);
Updating data in Table
Here is the code to update the data in the table.
const mysql = require('mysql');
const pool = [Link]({
connectionLimit :100,//important
host :'localhost',
user :'root',
password :'',
database :'todolist',
debug :false
});
// update rows
function updateRow(data){
let updateQuery ="UPDATE ?? SET ?? = ? WHERE ?? = ?";
let query = [Link](updateQuery,["todo","notes",[Link],"user",[Link]]);
// query = UPDATE `todo` SET `notes`='Hello' WHERE `name`='shahid'
[Link](query,(err, response)=>{
if(err){
console. error(err);
return;
}
// rows updated
console. log([Link]);
});
}
7/10
// timeout just to avoid firing query before connection happens
setTimeout(() => {
// call the function
// update row
updateRow({
"user": "Shahid",
"value": "Just updating a note"
});
},5000);
Deleting Rows in the table
Here is the code to delete a row from the table.
const mysql = require('mysql');
const pool = [Link]({
connectionLimit :100,//important
host :'localhost',
user :'root',
password :'',
database :'todolist',
debug :false
});
function deleteRow(userName){
let deleteQuery ="DELETE from ?? where ?? = ?";
let query = [Link](deleteQuery,["todo","user", userName]);
// query = DELETE from `todo` where `user`='shahid';
[Link](query,(err, response)=>{
if(err){
console. error(err);
return;
}
// rows deleted
console. log([Link]);
});
}
// timeout just to avoid firing query before connection happens
8/10
setTimeout(() => {
// call the function
// delete row
deleteRow('shahid');
},5000);
Calling MySQL Stored Procedure Using Node
You can also call a stored procedure using [Link]. If you don’t have stored procedure
created in MySQL, you can refer to the code below to do the same.
DELIMITER $$
CREATEPROCEDURE`getAllTodo`()
BEGIN
SELECT*FROM todo;
END$$
DELIMITER ;
Here is the code to call the stored procedure from the code.
const mysql = require('mysql');
const pool = [Link]({
connectionLimit :100,//important
host :'localhost',
user :'root',
password :'',
database :'todolist',
debug :false
});
function callSP(spName){
let spQuery ='CALL ??';
let query = [Link](spQuery,[spName]);
// CALL `getAllTodo`
[Link](query,(err, result)=>{
if(err){
console. error(err);
return;
}
// rows from SP
9/10
console. log(result);
});
}
// timeout just to avoid firing query before connection happens
setTimeout(() => {
// call the function
// call sp
callSP('getAllTodo')
},5000);
Conclusion :
MySQL is one of a widely used database engine in the world and with Node it really
works very well. Node MySQL pooling and event-based debugging are really powerful
and easy to code.
Further reading:
Node-mysql Github
Pro MERN Stack: Full Stack Web App Development with Mongo, Express, React,
and Node
10/10