AppGeer
AppGeer

Reputation: 745

Socket.io and MySQL Connections

I'm working on my first node.js-socket.io project. Until now i coded only in PHP. In PHP it is common to close the mysql connection, when it is not needed any more. My Question: Does it make sense to keep just one mysql-connection during server is running open, or should i handle this like PHP. Info: In the happy hours i will have about 5 requests/seconds from socket clients and for almost all of them i have to make a mysql_crud.

Which one would you prefer?

io = require('socket.io').listen(3000); var mysql = require('mysql');
var connection = mysql.createConnection({
    host:'localhost',user:'root',password :'pass',database :'myDB'
});

connection.connect();  // and never 'end' or 'destroy'
// ...

or

var app = {};
app.set_geolocation = function(driver_id, driver_location) {
    connection.connect(); 
    connection.query('UPDATE drivers set ....', function (err) {
        /* do something  */
    })
    connection.end();
}
...

Upvotes: 0

Views: 5964

Answers (1)

Stefan Rogin
Stefan Rogin

Reputation: 1527

The whole idea of Node.js is async io (that includes db queries). And the rule with a mysql connection is that you can only have one query per connection at a time. So you either make a queue and have a single connection, as in the first option or create a connection each time as with option 2.

I personally would go with option 2, as opening and closing connections are not such a big overhead.

Here are some code samples to help you out: https://codeforgeek.com/2015/01/nodejs-mysql-tutorial/

Upvotes: 1

Related Questions