0

I am using NodeJs along with MySQL. I am using node-mysql after looking at MySQL with Node.js. Now the problem is I am trying to make db connection only once and using GETs inside it but it's not working. Code:

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'example.org',
  user     : 'bob',
  password : 'secret',
});

connection.connect(function(err) {
    // connected! (unless `err` is set)
    app.get('/hello',function(req,res){
        console.log('Hello'); 
        res.send('Hi');
    });

});

But the above code is not working. It is not recognizing the route. But making a connection inside every get function works. I should be doing something wrong. Is there any way such that I can connect to the Db only once ?

Community
  • 1
  • 1
Srinath Mandava
  • 3,384
  • 2
  • 24
  • 37

1 Answers1

1

You should move your call to app.get to the top level scope of the file. These calls are declarative and should be thought of more like configuring your application than the application's business logic. From the mysql docs, the connection object will automatically implicitly open a connection to the database if connection.query is called and a connection is not yet established. That sounds like the mechanism you should take advantage of.

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'example.org',
  user     : 'bob',
  password : 'secret',
});

app.get('/hello',function(req,res){
  console.log('Hello');
  connection.query('select * from users', function (error, result) {
    res.send('Hi');
  });
});
Peter Lyons
  • 142,938
  • 30
  • 279
  • 274