0

I want to make queries for mySQL DB from node.js, using socket.io, what's the best way for doing it as modular as possible?

this is what I did so far: (it works fine, but is there a better way?)

var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, mysql = require('mysql')
, http = require('http');   
var query = "SELECT * FROM table";

app.listen(88);  
io.sockets.on('connection', function (socket) 
{ 
     socket.on('queryReq', function(){queryFunc(query, socket);
});

function queryFunc(query, socket){  
var connection = mysql.createConnection({
  host : 'localhost',
  user : 'admin',
  password : '1234'
});
    connection.query(query, function(err, rows){
    if(err != null) {
        socket.emit("DBnews", "Error in Query: " + err);
    }else{// Shows the results:
    for (var i=0; i<rows.length; i++){
       console.log(rows[i]);
       socket.emit("DBnews", '\n'+JSON.stringify(rows[i]));
    }
    }    
    connection.end();// Close connection
console.log("Disconnected!");
});
}
Aviram Netanel
  • 12,633
  • 9
  • 45
  • 69

1 Answers1

1

Don't keep creating/ending your db connection for each query. You can connect to the db on app startup, and then close it at the exit [process.on('exit',...)]. Other than that, your code looks just fine for querying the db from a socket event. It's really no different than querying the db from a GET or POST request.

Chris
  • 1,611
  • 12
  • 11
  • Hi Chris, Thanks for the quick response. I've added this line at the end: process.on('exit',function(){connection.end()}); but how can I check if it really works? – Aviram Netanel Dec 30 '13 at 14:48
  • 1
    Do you use phpMyAdmin? If so, you can monitor processes/connections. If you don't, look here: http://stackoverflow.com/questions/824428/number-of-db-connections-opened – Chris Dec 30 '13 at 14:54