You are on page 1of 26

16/01/2020 Node.

js MySQL Tutorial - Codeforgeek

# Mysql # Node.Js # Tutorial

Node.js MySQL Tutorial


 428843 Views  5 Apr 2019  18 min read

Shahid

Founder of Codeforgeek. Technologist. Published Author. Engineer. Content Creator. Teaching Everything I learn!

MySQL Tutorial Node JS Production Scheduling

Node.js and MySQL is one of the necessary binding needed for any web application. MySQL is
one of the most popular open source database in world and ef cient as well. Almost every
popular programming language like Java or PHP provides driver to access and perform
operations with MySQL.

In this tutorial i am trying to cover code for learning and code for production. So if you know this
already and looking for ready made code for production. Click here to jump there directly.

https://codeforgeek.com/nodejs-mysql-tutorial/ 1/26
16/01/2020 Node.js MySQL Tutorial - Codeforgeek

Introduction:
Node.js is rich with number of popular packages registered at package registry called NPM. Most
of them are not so reliable to use for production but there are some on which we can rely upon.
For MySQL there is one popular driver called node-mysql.

In this tutorial, I am going to cover the following points related to Node.js and MySQL.

Sample code to get started.

Code for Production.

Testing concurrent users.

If you are new to Node and Express then you won’t regret taking our Node course. Its
FREE!

Sample code to get started.


Project directory:

---node_modules
-----+ mysql
-----+ express
---index.js
---package.json

package.json

https://codeforgeek.com/nodejs-mysql-tutorial/ 2/26
16/01/2020 Node.js MySQL Tutorial - Codeforgeek

{
  "name": "node-mysql",
  "version": "0.0.1",
  "dependencies": {
    "express": "^4.10.6",
    "mysql": "^2.5.4"
  }
}

Install dependencies using


Ad

Creative Web Designing


Agency - Seo Friendly
Webisite

VISIT SITE

npm install

Here is sample code which connects to Database and perform SQL query.

var mysql      = require('mysql');


var connection = mysql.createConnection({
  host     : 'localhost',
  user     : '< MySQL username >',
  password : '< MySQL password >',
  database : '<your database name>'
});

connection.connect();

connection.query('SELECT * from < table name >', function(err, rows, fields) {


  if (!err)
    console.log('The solution is: ', rows);
  else
    console.log('Error while performing Query.');
});

connection.end();

Make sure you have started MySQL on default port and changed the parameter in above code
then run this code using

node file_name.js

https://codeforgeek.com/nodejs-mysql-tutorial/ 3/26
16/01/2020 Node.js MySQL Tutorial - Codeforgeek

Code for production :

Above code is just for learning purpose and not for production payload. In production scenario is
different, there may be thousands of concurrent users which turns into tons of MySQL queries.
Above code won’t run for concurrent users and here is a proof. Let’s modify our code little bit and
add Express routes in that, here it is.

test.js ( Change database settings in code )

var express    = require("express");


var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : '',
  database : 'address_book'
});
var app = express();

connection.connect(function(err){
if(!err) {
    console.log("Database is connected ... nn");    
} else {
    console.log("Error connecting database ... nn");    
}
});

app.get("/",function(req,res){
connection.query('SELECT * from user LIMIT 2', function(err, rows, fields) {
connection.end();
  if (!err)
    console.log('The solution is: ', rows);
  else
    console.log('Error while performing Query.');
  });
});

app.listen(3000);

https://codeforgeek.com/nodejs-mysql-tutorial/ 4/26
16/01/2020 Node.js MySQL Tutorial - Codeforgeek

Install siege in your system. I use this command to install it in Ubuntu.

apt-get install siege

then run our node and server and following command.

node test.js

siege -c10 -t1M http://localhost:3000

Assuming you are running Node server on Port 3000.


Here is the output.

https://codeforgeek.com/nodejs-mysql-tutorial/ 5/26
16/01/2020 Node.js MySQL Tutorial - Codeforgeek

In above code, we are allowing it to run for standalone connection i.e one connection at a time
but reality is bit different. You may get 100 or 1000 connection at one particular time and if your
server is not powerful enough to serve those request then at least it should put them in queue.

Pool connection in MySQL :

Connection Pooling is mechanism to maintain cache of database connection so that connection


can be reused after releasing it. In Node mysql, we can use pooling directly to handle multiple
connection and reuse the connection. Let’s write same code with pooling and check whether it
can handle multiple connection or not.

test.js

var express   =    require("express");


var mysql     =    require('mysql');
var app       =    express();

var pool      =    mysql.createPool({


    connectionLimit : 100, //important
    host     : 'localhost',
    user     : 'root',
    password : '',
    database : 'address_book',
    debug    :  false
});

function handle_database(req,res) {
   
    pool.getConnection(function(err,connection){
        if (err) {
          res.json({"code" : 100, "status" : "Error in connection database"});
          return;
https://codeforgeek.com/nodejs-mysql-tutorial/ 6/26
16/01/2020 Node.js MySQL Tutorial - Codeforgeek

        }  

        console.log('connected as id ' + connection.threadId);


       
        connection.query("select * from user",function(err,rows){
            connection.release();
            if(!err) {
                res.json(rows);
            }          
        });

        connection.on('error', function(err) {      
              res.json({"code" : 100, "status" : "Error in connection database"});
              return;    
        });
  });
}

app.get("/",function(req,res){-
        handle_database(req,res);
});

app.listen(3000);

Run the app using

node test.js

and re 10 concurrent users for 1 minute using siege by using this command.

siege -c10 -t1M http://localhost:3000

https://codeforgeek.com/nodejs-mysql-tutorial/ 7/26
16/01/2020 Node.js MySQL Tutorial - Codeforgeek

Here is output.

**UPDATE**

You can directly use pool.query() which internally will acquire connection and release it when
query is executed. In my personal code review experience, majority of the developers often
forget to release the acquired connection which in turns creates bottleneck and database load.

Refer the code snippet below:

test.js

var express   =    require("express");


var mysql     =    require('mysql');
var app       =    express();

var pool      =    mysql.createPool({


    connectionLimit : 100, //important
    host     : 'localhost',
    user     : 'root',
    password : '',
    database : 'address_book',
    debug    :  false
});

function handle_database(req,res) {
       // connection will be acquired automatically
       pool.query("select * from user",function(err,rows){
        if(err) {
            return res.json({'error': true, 'message': 'Error occurred'+err});
        }

                //connection will be released as well.


https://codeforgeek.com/nodejs-mysql-tutorial/ 8/26
16/01/2020 Node.js MySQL Tutorial - Codeforgeek
                res.json(rows);
       });
}

app.get("/",function(req,res){-
        handle_database(req,res);
});

app.listen(3000);

I have used this function in a production environment with heavy payload and it works like
charm.

Executing Queries

Let’s learn how to execute queries using Node.js.

Inserting Rows into Table

Best Web Development Service - At a


Reasonable Price
we are providing best range of web development
service for your business.
Ad

Here is the code to add new rows in the table.

const mysql = require('mysql');

const pool = mysql.createPool({


    connectionLimit : 100, //important
    host     : 'localhost',
    user     : 'root',
    password : '',
    database : 'todolist',
d b f l
https://codeforgeek.com/nodejs-mysql-tutorial/ 9/26
16/01/2020 Node.js MySQL Tutorial - Codeforgeek
    debug    :  false
});

// add rows in the table

function addRow(data) {
    let insertQuery = 'INSERT INTO ?? (??,??) VALUES (?,?)';
    let query = mysql.format(insertQuery,["todo","user","notes",data.user,data.value]);
    pool.query(query,(err, response) => {
        if(err) {
            console.error(err);
            return;
        }
        // rows added
        console.log(response.insertId);
    });
}

// timeout just to avoid firing query before connection happens

setTimeout(() => {
    // call the function
    addRow({
        "user": "Shahid",
        "value": "Just adding a note"
    });
},5000);

The mysql.format 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 = mysql.createPool({


    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 = mysql.format(selectQuery,["todo","user", userName]);
    // query = SELECT * FROM `todo` where `user` = 'shahid'
    pool.query(query,(err, data) => {
        if(err) {
https://codeforgeek.com/nodejs-mysql-tutorial/ 10/26
16/01/2020 Node.js MySQL Tutorial - Codeforgeek

            console.error(err);
            return;
        }
        // rows fetch
        console.log(data);
    });
}

// timeout just to avoid firing query before connection happens

setTimeout(() => {
    // call the function
    // select rows
    queryRow('shahid');
},5000);

Ad

Drag and drop data


migration - REST API to
Cloud Warehouse

VISIT SITE

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 = mysql.format(insertQuery,["todo","user","notes",values]);

Updating data in Table

Here is the code to update data in the table.

const mysql = require('mysql');

const pool = mysql.createPool({


    connectionLimit : 100, //important
    host     : 'localhost',
    user     : 'root',

    password : '',
    database : 'todolist',
    debug    :  false
});

// update rows

function updateRow(data) {
https://codeforgeek.com/nodejs-mysql-tutorial/ 11/26
16/01/2020 Node.js MySQL Tutorial - Codeforgeek
p ( ) {
    let updateQuery = "UPDATE ?? SET ?? = ? WHERE ?? = ?";
    let query = mysql.format(updateQuery,["todo","notes",data.value,"user",data.user]);
    // query = UPDATE `todo` SET `notes`='Hello' WHERE `name`='shahid'
    pool.query(query,(err, response) => {
        if(err) {
            console.error(err);
            return;
        }
        // rows updated
        console.log(response.affectedRows);
    });
}

// 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 = mysql.createPool({


    connectionLimit : 100, //important
    host     : 'localhost',
    user     : 'root',
    password : '',
    database : 'todolist',
    debug    :  false
});

function deleteRow(userName) {
    let deleteQuery = "DELETE from ?? where ?? = ?";
    let query = mysql.format(deleteQuery, ["todo", "user", userName]);
    // query = DELETE from `todo` where `user`='shahid';
    pool.query(query,(err, response) => {
        if(err) {
            console.error(err);
            return;
        }
        // rows deleted
        console.log(response.affectedRows);
    });
}

https://codeforgeek.com/nodejs-mysql-tutorial/ 12/26
16/01/2020 Node.js MySQL Tutorial - Codeforgeek

// timeout just to avoid firing query before connection happens

setTimeout(() => {
    // call the function
    // delete row
    deleteRow('shahid');
},5000);

Calling MySQL Stored Procedure Using Nodejs

You can also call a stored procedure using Node.js. If you don’t have stored procedure created in
MySQL, you can refer to the code below to do the same.

DELIMITER $$
 
CREATE PROCEDURE `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 = mysql.createPool({


    connectionLimit : 100, //important
    host     : 'localhost',
    user     : 'root',
    password : '',
    database : 'todolist',
    debug    :  false
});

function callSP(spName) {
    let spQuery = 'CALL ??';
    let query = mysql.format(spQuery,[spName]);
    // CALL `getAllTodo`
    pool.query(query,(err, result) => {

https://codeforgeek.com/nodejs-mysql-tutorial/ 13/26
16/01/2020 Node.js MySQL Tutorial - Codeforgeek

        if(err) {
            console.error(err);
            return;
        }
        // rows from SP
        console.log(result);
    });
}

// timeout just to avoid firing query before connection happens

setTimeout(() => {
    // call the function
    // call sp
    callSP('getAllTodo')
},5000);

Final comments :

Siege is a really powerful tool for the testing server under pressure. We have created 100
connection limit in code, so you might be wondering that after 100 concurrent connection code
will break. Well, let me answer it via code. Fire 1000 concurrent user for 1 minute and let’s see
how our code reacts.

siege -c1000 -t1M http://localhost:3000

If your MySQL server is con gured to handle such traf c at one socket then it will run and our
code will manage the scheduling of concurrent connection. It will serve 100 connection time but
rest 900 will be in the queue. So the code will not break.

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
https://codeforgeek.com/nodejs-mysql-tutorial/ 14/26
16/01/2020 Node.js MySQL Tutorial - Codeforgeek

Pro MERN Stack: Full Stack Web App Development with Mongo, Express, React, and Node

Learn SQL Interview Questions

Sponsored

2,3 BHK In North BLR For Less Than ₹ 36 L. Near SEZ, Aerospace Park.
Brigade Group

2 &3 BHK Apartments in Vijayanagar, Bangalore | Salarpuria Sattva Anugraha


Salarpuria Satta

Top 7 Overseas Education Consultants are within 5 kms from you.


Sulekha

Design Thinking | Stanford Executive Education


Great Learning

Pop Up For Extra Fun With Honor 9X


Honor 9X

Susan Boyle is So Skinny Now and Looks Gorgeous! (Photos)


Mortgage After Life

130 Comments Codeforgeek 


1 Login

 Recommend t Tweet f Share Sort by Best

Join the discussion…

LOG IN WITH
OR SIGN UP WITH DISQUS ?

Name

anshu • 7 months ago


router.get('/', function (req, res, next) {

do_queries = function (callback) {


db.all("SELECT * FROM user where id=?", 1, function (err, rows) {
if (err) {
callback(err);
return;
 } 
db.each("SELECT * FROM product where user_id=?", row.id, function (err, res2) {
if (err) {
callback(err);
return;
}
callback(null, res2); // think 'return'
});
});
}

t h dl f ti ( ){
https://codeforgeek.com/nodejs-mysql-tutorial/ 15/26
16/01/2020 Node.js MySQL Tutorial - Codeforgeek
see more

△ ▽ • Reply • Share ›

Shahid > anshu • 7 months ago


What is your problem?
△ ▽ • Reply • Share ›

arpit • 9 months ago


how to upload image using mysql node restful api plz help
△ ▽ • Reply • Share ›

Shahid Mod > arpit • 4 months ago


Check this article for the same.
△ ▽ • Reply • Share ›

Mark Edwards • a year ago


Note that the next release of Sequelize will be practically rewritten by MariaDB. Between
the now obsolete MySQL and MariaDB, we see who is taking node far more seriously.
△ ▽ • Reply • Share ›

Comments continue after advertisement

Yogesh • a year ago


Great post. Thanks for sharing.
△ ▽ • Reply • Share ›

Mark Feder • a year ago


Great !! thanks
△ ▽ • Reply • Share ›

Justin • a year ago


Great stuff, but if you are not using the most popular Node/MySQL ORM Sequelize, you will
be a wasting a ton of time of these intricacies.

https://github.com/sequeliz...
△ ▽ • Reply • Share ›

Shahid Mod > Justin • 4 months ago


Sequelize is very slow when we did benchmarking. Native drivers works the best.
△ ▽ • Reply • Share ›

Leo Arcos • 2 years ago


I have the following error when using the address of my server, with LOCALHOST or
127.0.0.1 it works perfectly:
Error: ER_ACCESS_DENIED_ERROR: Access denied for user 'idsprueba'@'static-201-
245-170-116.stat...' (using password: YES)
at Handshake.Sequence._packetToError
(C:UsersLeoDocumentsElectronAppsNutSisnode_modulesmysqllibprotocolsequencesSeque
at Handshake.ErrorPacket
(C:UsersLeoDocumentsElectronAppsNutSisnode_modulesmysqllibprotocolsequencesHand
at Protocol._parsePacket
(C:UsersLeoDocumentsElectronAppsNutSisnode_modulesmysqllibprotocolProtocol.js:279:2
at Parser.write
(C:UsersLeoDocumentsElectronAppsNutSisnode_modulesmysqllibprotocolParser.js:76:12)
at Protocol.write
(C:UsersLeoDocumentsElectronAppsNutSisnode_modulesmysqllibprotocolProtocol.js:39:16
at Socket.
(C:UsersLeoDocumentsElectronAppsNutSisnode_modulesmysqllibConnection.js:103:28)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at readableAddChunk (_stream_readable.js:176:18)
at Socket.Readable.push (_stream_readable.js:134:10)
--------------------
at Protocol._enqueue
(C:UsersLeoDocumentsElectronAppsNutSisnode_modulesmysqllibprotocolProtocol.js:145:4
at Protocol.handshake
(C U L D t El t A N tSi d d l llib t lP t l j 52 23
https://codeforgeek.com/nodejs-mysql-tutorial/ 16/26
16/01/2020 Node.js MySQL Tutorial - Codeforgeek
(C:UsersLeoDocumentsElectronAppsNutSisnode_modulesmysqllibprotocolProtocol.js:52:23
at Connection.connect
(C:UsersLeoDocumentsElectronAppsNutSisnode_modulesmysqllibConnection.js:130:18)
at logIn
△ ▽ • Reply • Share ›

Shahid (UnixRoot) Shaikh > Leo Arcos • 2 years ago


Try with IP of the Server.
△ ▽ • Reply • Share ›

Omid • 3 years ago


Hello
I try it in mac (with Mamp)
but nothing happen and wait in same line
what is problem?
△ ▽ • Reply • Share ›

silant • 3 years ago


Installed mysql however npm appears to think that it is extraneous. I have not been able to
find any reason why this is so. My only guess is that mysql is somehow already installed
with npm by default?

If not, then I should just ignore the error?


△ ▽ • Reply • Share ›

Comments continue after advertisement

Raghu teja • 3 years ago


Hi Shahid,
can you reply to my post:
http://stackoverflow.com/qu...
△ ▽ • Reply • Share ›

Shahid (UnixRoot) Shaikh > Raghu teja • 3 years ago


Seems you already solved it.
△ ▽ • Reply • Share ›

mark edwards • 3 years ago


mariadb has its own node interface (https://github.com/mscdex/n.... do you think that either
could be used, and used interchangeably?
△ ▽ • Reply • Share ›

Shahid (UnixRoot) Shaikh > mark edwards • 3 years ago


I use node mysql for MariaDB and it works!
△ ▽ • Reply • Share ›

mark edwards > Shahid (UnixRoot) Shaikh • 3 years ago


>> mariadb has its own node interface (https://github.com/mscdex/n....

do you think either could be used completely interchangably? and could


mariadb-node be used for mysql?

i am now wondering why the mariaDB people felt like they needed their own
node-interface.

update: lets see what github has to say about it:


https://github.com/mscdex/n...
△ ▽ • Reply • Share ›

sai • 3 years ago


how to put port number(3307) in db connection?
△ ▽ • Reply • Share ›

Shahid (UnixRoot) Shaikh > sai • 3 years ago


Just add port: 3307 in the mysql configuration code.
△ ▽ • Reply • Share ›

Muhammad Hafid • 3 years ago


https://codeforgeek.com/nodejs-mysql-tutorial/ 17/26
16/01/2020 Node.js MySQL Tutorial - Codeforgeek
Muhammad Hafid 3 years ago
Thanks for share sir.
△ ▽ • Reply • Share ›

Muhammad Hafid • 3 years ago


Running good...
△ ▽ • Reply • Share ›

JohnD • 3 years ago


I was trying this sample and found the first set of code where you initially do a siege and it
produces the error, may be better to just use a browser instead of siege as always the 2nd
call to that node server code would error.

I took it a step further and put the createConnection and connect within the app.get function
and did some stress testing using an external RDS mysql. I found that straight
createConnection vs createPool connection method results in almost no transaction rate
difference (390trans/sec on a siege -c200 -t30s -d1

That leads me to really question the benefit of that added pool code complexity. I get the
idea of reusing a pooled cached connection but not sure where the real benefit is?

I tried but was unable to even break the straight app.get {createConnection / connect /
query / end} type connection without pooled connections.
△ ▽ • Reply • Share ›

JohnD > JohnD • 3 years ago


actually i was wrong. I missed the connection failed errors. under a siege -c200 -
t60s -d3 non-pooled connect resulted in 16 fails out of about 8000 hits. So I did
prove pooled connection is needed to queue under stress. Thanks for a great
learning tool
△ ▽ • Reply • Share ›

Shahid (UnixRoot) Shaikh > JohnD • 3 years ago


Your welcome John :)
△ ▽ • Reply • Share ›

Comments continue after advertisement

fatimaz • 3 years ago


thanks for your tuto
△ ▽ • Reply • Share ›

matt • 3 years ago


Hi ,
how can we use it in different files like for example employee.js and inventory.js
like iam unable to find example wherein you define database name and connect in app.js
and use some thing so that we can access db obj in routes file employee.js and inventory.js
△ ▽ • Reply • Share ›

Shahid (UnixRoot) Shaikh > matt • 3 years ago


Hi matt,
I do it like this.
- Create a separate file containing code for DB handling such as Connection etc.
- Create different model files that deals with database operation and call our DB file
to handle DB stuff.
- Include these model files in controller where our routes is and call those functions
on API call.

Hope it help.s
△ ▽ • Reply • Share ›

JTorres • 3 years ago


Fantastic tutorial , but Its happended an strage thing:

connection.query doesnt work when i set a sleep() function as it: (Any idea?)

connection.query('UPDATE......')
sleepFor(2000);

https://codeforgeek.com/nodejs-mysql-tutorial/ 18/26
16/01/2020 Node.js MySQL Tutorial - Codeforgeek
function sleepFor( sleepDuration ){
var now = new Date().getTime();
while(new Date().getTime() < now + sleepDuration){ /* do nothing */ }
}
△ ▽ • Reply • Share ›

JTorres • 3 years ago


Fantastic tutorial , but Its happended and strage thing:

connection.query doesnt work when i set a sleep() function as it: (Any idea?)

connection.query('UPDATE......')
sleepFor(2000);

function sleepFor( sleepDuration ){


var now = new Date().getTime();
while(new Date().getTime() < now + sleepDuration){ /* do nothing */ }
}
△ ▽ • Reply • Share ›

ak • 3 years ago
i am facing problem with node and mysql
whenever i fetch data mysql which is having more than 30k rows and display the result as
json .
node is not performing well.
i have to get the mysql result in array , so there is will be for loop which is blocking event
△ ▽ • Reply • Share ›

Shahid (UnixRoot) Shaikh > ak • 3 years ago


This is where "streams" comes in handy.

30K JSON doc won't get handled in memory.


△ ▽ • Reply • Share ›

Tunde • 3 years ago


Having problem to connect to server ,trying to use this code,Need help pls
△ ▽ • Reply • Share ›

Shahid (UnixRoot) Shaikh > Tunde • 3 years ago


Is MySQL up and running ? If so, is the connection string is correct ?
△ ▽ • Reply • Share ›

Comments continue after advertisement

Daniel Berlanga • 3 years ago


I'm sorry if this question has already been done, since there's a lot of comments and I didn't
read them all...
You are creating a pool of connections, but nodejs is a non-concurrent server, therefore
even if you have more than one connection (of the pool), only one will be used at the same
time (unless you also have a pool of nodejs servers, managed by some load-balancer like
nginx)

So my point is, there's no sense of creating pooled mysql connections, since each server
will only use once at a time, right?
Actually I came to this conclussion after running the following test with ab:
ab -c 1000 -t 30 localhost:7777/test

# In a mysql 100 pool connection


> Requests per second: 662.82 [#/sec] (mean)
> Time per request: 1508.716 [ms] (mean)

# In a mysql 1 pool connection


> Requests per second: 1346.24 [#/sec] (mean)
> Time per request: 742.811 [ms] (mean)

# In a mysql no-pool (direct) connection


> Requests per second: 1732.07 [#/sec] (mean)
> Time per request: 577.344 [ms] (mean)

Knowing this isn't it better to have just one direct connection for each nodejs server?
https://codeforgeek.com/nodejs-mysql-tutorial/ 19/26
16/01/2020 Node.js MySQL Tutorial - Codeforgeek
Knowing this, isn t it better to have just one direct connection for each nodejs server?
The main problem with your code, is that you are doing connection.end();
You can (and must) leave it open for future requests, that's the reason your siege is failing...
△ ▽ • Reply • Share ›

Shahid (UnixRoot) Shaikh > Daniel Berlanga • 3 years ago


Hey Daniel,

This is the awesome question so far and let me answer it with my understanding.

First, about the non-concurrent server, I believe you meant single thread ? That's
true but let's get to the point of threading a little bit later.

Regarding MySQL pool, what is happening is Node does accept a lot of connection
at once and generate thread inside for the various different ops, in this case, MySQL
queries. So you have to say 1000 connections and all of them want to query 1000
SELECT queries.

If I don't use Pool and just one connection, then I have to do this.

Repeat till 100


Execute query.
Get the next request.
Done

This will block your event loop, we want to execute 1000 queries in parallel. But,
MySQL does execute them in some queuing manner which is not our concern at
this moment. With pool, I can create 100 connections at a time, and a minute
MySQL completes one SQL query, I am releasing it to Pool so that same can be
reused (Performing connection does take time and HTTP request).

Hope I answered this part. Regarding threading, libev (event loop of Node) performs
the internal thread management by giving programmer one single thread. So for
each I/O, Network call there are different threads (or maybe it reuse some, not
sure).
△ ▽ • Reply • Share ›

luis • 4 years ago


Hello Shahid i had an error with this part<

if(err){
connection.release();
log.error(&#039Connecting to database&#039)
context.fail(null);
}

TypeError: Cannot read property &#039release&#039 of undefined

when i remove con.release (); my code works properly


△ ▽ • Reply • Share ›

Shahid (UnixRoot) Shaikh > luis • 4 years ago


Yes, it was my mistake. Thanks :)
△ ▽ • Reply • Share ›

luis > Shahid (UnixRoot) Shaikh • 4 years ago


i see , what about if i wrote wrong the query? it never ends , stay in the part
Connected as id xxxx
how should i catch those errors?? thank you for your answer
△ ▽ • Reply • Share ›

Shahid (UnixRoot) Shaikh > luis • 4 years ago


SQL query level error will come under the error callback variable in
connection.query() function.

SQL DB level error will come under error callback variable in


connect() function.
△ ▽ • Reply • Share ›

luis > Shahid (UnixRoot) Shaikh • 4 years ago

https://codeforgeek.com/nodejs-mysql-tutorial/ 20/26
16/01/2020 Node.js MySQL Tutorial - Codeforgeek
Thank you so much sensei.
△ ▽ • Reply • Share ›

luis > luis • 4 years ago


So at the end this is my code working properly :function
handle_database(req,res){
pool.getConnection(function(err,con) {
// body...
if(err){
log.error('Connecting to database')
context.fail(err);
}
log.info('Connected as id '+ con.threadId);

con.query('select * from persons', function(err,rows){


con.release();

if(err){
log.info('Resolving the query')
context.fail(err);
}
log.info('Connection succefull')
t t d( ll)
see more

△ ▽ • Reply • Share ›

Shahid (UnixRoot) Shaikh > luis • 4 years ago


Your code is correct :) And so is mine. This is the beauty of
JavaScript. I did !err condition which was not accurate I believe. Yours
is correct and should work like a charm.
△ ▽ • Reply • Share ›

Shekhar • 4 years ago


what is the latest mysql version
△ ▽ • Reply • Share ›

Shahid (UnixRoot) Shaikh > Shekhar • 4 years ago


Check on MySQL homepage.
△ ▽ • Reply • Share ›

Brijesh • 4 years ago


Sir, what will happen if I will not release the connection after performing any query. I am
connecting with database only once and after create or select queries I am not releasing
connection. It will effect to my application or not. Thanks in advance.
△ ▽ • Reply • Share ›

Shahid (UnixRoot) Shaikh > Brijesh • 4 years ago


Yes, it can crash your application.

You will receive "Connection limit reached" error.

Make sure you return the used connection properly.


△ ▽ • Reply • Share ›

Brijesh > Shahid (UnixRoot) Shaikh • 4 years ago


Hi Shahid, thanks for the reply I changes my code as
mysql_connection.getConnection(function(err, connection) {
if(err){
console.log(" getConnection error: "+err);
callback("",'database');
}
connection.query('SELECT * FROM portfolio.users WHERE ' +
'email ="'+ request.email+'"', function(err,res) {
if(err){
console.log("database error" + err);
callback("",'database');
}
https://codeforgeek.com/nodejs-mysql-tutorial/ 21/26
16/01/2020 Node.js MySQL Tutorial - Codeforgeek
else if(res == 'null' || res == ''){
console.log("n data");
connection.release();
callback("",'null');
}else{
console.log("in3");
console.log('%s: %s \n', res[0].email, res[0].password);
connection.release();
callback("",res[0]);
}
});
});

I need to know if I am using two callbacks so I have to release cnnections in


both the places.
△ ▽ • Reply • Share ›

Genting Highland • 4 years ago


Greetings! I've been following your blog for
some time now and finally got the courage to go ahead
and give you a shout out from Lubbock Texas! Just wanted to tell you keep up the fantastic
job!
△ ▽ • Reply • Share ›

Sandeep • 4 years ago


I am getting following error

C:\Users\Cres\NodeJS\DatabaseTest>node test
{ [Error: ER_BAD_DB_ERROR: Unknown database 'nodejs']

Sponsored

2,3 BHK In North BLR For Less Than ₹ 36 L. Near SEZ,


Aerospace Park.
Brigade Group

2 &3 BHK Apartments in Vijayanagar, Bangalore |


Salarpuria Sattva Anugraha
Salarpuria Satta

Design Thinking | Stanford Executive Education


Great Learning

Pop Up For Extra Fun With Honor 9X


Honor 9X

Susan Boyle is So Skinny Now and Looks Gorgeous!


(Photos)
Mortgage After Life

Have This At Night To Detox Your Lungs in A Week !


फेफड़े िडटॉ
Lungs Cleanser

https://codeforgeek.com/nodejs-mysql-tutorial/ 22/26
16/01/2020 Node.js MySQL Tutorial - Codeforgeek

CodeFund has
paid out over
$170K to open
source projects in
2019. Do you
qualify? 🤔
ethical ad by CodeFund

Looking for a
Node.js developer?

Hire Now

Subscribe to our
Newsletter

Your name

https://codeforgeek.com/nodejs-mysql-tutorial/ 23/26
16/01/2020 Node.js MySQL Tutorial - Codeforgeek

Email

Submit

report this ad

 Related Articles

Programming Trends in 2019 &#8211; Why React Matters

https://codeforgeek.com/nodejs-mysql-tutorial/ 24/26
16/01/2020 Node.js MySQL Tutorial - Codeforgeek

Parse large XML les in Node

How to Deploy Your Awesome Angular App on Heroku

Subscribe to our Newsletter

Name

Email

https://codeforgeek.com/nodejs-mysql-tutorial/ 25/26
16/01/2020 Node.js MySQL Tutorial - Codeforgeek

Submit

Follow us

Top Articles

- Real time Global Aviation Data using Aviationstack


- Forward/Reverse Geocoding Made easy with Positionstack
- Top Machine Learning Frameworks For Web Development
- How Online Businesses Design Their Websites to Attract More Visitors

Top Courses

- Getting Started With Node - Course

Links

- About Us
- Services
- Contact Us
- Terms Services
- Privacy & Policy

Links

- Advertise with us
- Best Programming Tutorial
- Resources
- Start Here

Copyright © 2019 codeforgeek.com All Rights Reserved

Built with love using Node.js. Checkout our Services page for details.

https://codeforgeek.com/nodejs-mysql-tutorial/ 26/26

You might also like