5
votes

Using sequel pro I have created a database called test. It has one table called users. In that table there is one user -> id=1, name=Phantom.

I have installed the mysql node module

When I run the code below I get The solution is: undefined.

Can anyone advise how I can connect to database and show the users?

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

connection.connect();

connection.query('SELECT * from users', function(err, rows, fields) {
  if (err) throw err;
  console.log('The solution is: ', rows);
});

connection.end();

It shows the following error :

Error: connect ETIMEDOUT at Connection._handleConnectTimeout (/Users/fitz035/Desktop/sony/presave/node_modules/mysql/lib/Connection.js:425:13)

I am running the db through MAMP. These are the db settings :

Host:   localhost 
Port: 8889 
User:   root 
Password:   root 
Socket: /Applications/MAMP/tmp/mysql/mysql.sock
2
Check the err parameter in the callback to see, what went wrong. From your code I guess, the connection was closed, before the actual query went through.Sirko
@Sirko updated the questionuser6002037
Have you verified, that your database is actually running (on that port)?Sirko
If your db is running on port 8889, you should pass that as an additional parameter to the connection. The default mysql port is 3306, where your app wont find any server right now. As an alternative you can pass the socket directly as shown here: stackoverflow.com/a/26465986/1169798Sirko

2 Answers

6
votes

Node is asynchronous, so connection.end() is likely to happen before your query calls back. Also, specify the port Mysql is running on when non-standard.

try this :

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : 'root',
  database : 'test',
  port: 8889
});

connection.connect();

connection.query('SELECT * from users', function(err, rows, fields) {
    if(err) console.log(err);
    console.log('The solution is: ', rows);
    connection.end();
});
1
votes

If it on VPS configured with Firewall, you need to whitelist your IP via SSH. Otherwise it still throws exactly above error even after adding via cPanel's RemoteMYSQl

# csf -a [RemoteIP]
# csf -r 

You can do it quickly via WHM too. Just posted as it may help someone.