简体   繁体   中英

felixge/node-mysql coudn't connect to database

I installed the felixge/node-mysql via npm ( npm install mysql ), and now i want to connect to the mysql database, but every time I try to connect this error happens:

{ [Error: connect ECONNREFUSED]
  code: 'ECONNREFUSED',
  errno: 'ECONNREFUSED',
  syscall: 'connect' }
undefined

my nodejs source:

var mysql = require("mysql")
var db = mysql.createClient({
    host:"localhost",
    user:"root",
    password:"root"
});

db.query("SELECT 1",function(err,result,fields){
    if(err) {
        console.log(err);
    }
    console.log(result);
});

But i can easily access to my MySQL database via command line:

[user@host] $ mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.5.18-log Source distribution

Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> SELECT 1
    -> ;
+---+
| 1 |
+---+
| 1 |
+---+
1 row in set (0.00 sec)

mysql> 

Can anybody help me what is my mistake?

You need to set the socketPath

mysql = require('mysql');
var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : 'password',
    socketPath  : '/var/run/mysqld/mysqld.sock',

});

I had to modify the mysql configuration file. I commented out skip-networking and it fixed my problem.

If anybody can explain me why is that good I would thank it.

I use MAMP on MacOSX, remember add this

"socketPath": "/Applications/MAMP/tmp/mysql/mysql.sock"

{
    "host": "localhost",
    "port": 3306,
    "user": "nodejs",
    "password": "nodejs",
    "database": "crawler",
    "socketPath": "/Applications/MAMP/tmp/mysql/mysql.sock"
}

When you connect to mysql with node-mysql, you need to specify your hostname. If you're on linux you can find out using the command : hostname

So you know, i have the same problem i can connect to mysql via command line without specify the hostname but in node you need to change it. At least in my case. (v0.4.10) Why ? I'm not sure so maybe someone else have an idea.

var mysql = require("mysql")
var db = mysql.createClient({
    host: --- put what you got from the hostname command ---,
    user:"root",
    password:"root"
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM