Can't connect to localhost database from node.js server

Nikolai picture Nikolai · Jul 5, 2013 · Viewed 18.6k times · Source

Been having a lot of trouble trying to connect to to my localhost database. I've tried using the mysql and mysql-simple node modules but in both cases I just can't get it to connect.

Here's what I used with the 'mysql' module:

var mysql = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  port     : '8000',
  user     : 'uber',
  password : 'pass',
});

connection.connect(function(err) {
      if (err) throw err;

      console.log('Connection Successful');
});


connection.query('USE someDB', function(err) {
  if (err) throw err;

  console.log('Query Successful');
});

And here' what I used with the 'mysql-simple' module:

var database = require('mysql-simple');
database.init('uber', 'pass', 'mysql', 'localhost', 8000);

database.querySingle('SELECT Host FROM user', function(err, results) {
    if (err) {
        console.log('error fetching some active users: ' + err);
        return;
    }
    log('Query Successful');
    for (var i = 0; i < results.length; i++)
        console.log('got active user ' + results[i]);
}

In both cases, when I run my node.js server, it never logs that its connected. I've tried replacing localhost with '127.0.01' and creating a new user to make sure the password is correct, but to no avail. Why isn't it connecting?

Thanks

Answer

Panos Papadopoulos picture Panos Papadopoulos · Jul 12, 2014

It's most likely that networking is turned off, that means that mysql server communicates with clients via UNIX sockets and not via TCP/IP. You can check that out running mysql client and run "status" command. If you see port number there, then your mysql server communicates via TCP/IP, or else you'll see something like "socket pathname…", get the pathname and give it to node.js connection parameters, e.g.

... socketPathname: '/opt/lampp/var/...', ...

Check that out in https://github.com/felixge/node-mysql page (search for "socketPathname")

Hope, that's your problem.