【问题标题】:felixge/node-mysql coudn't connect to databasefelixge/node-mysql 无法连接到数据库
【发布时间】:2011-11-27 14:08:07
【问题描述】:

我通过 npm (npm install mysql) 安装了felixge/node-mysql,现在我想连接到 mysql 数据库,但每次尝试连接时都会发生此错误:

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

我的nodejs源码:

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);
});

但我可以通过命令行轻松访问我的 MySQL 数据库:

[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> 

谁能帮帮我我的错误是什么?

【问题讨论】:

  • 你有一个拼写错误console.log(results);应该读作console.log(result);
  • 问题仍然存在。顺便说一句谢谢
  • 我不确定,但也许模块不喜欢不使用数据库的 SELECT。尝试连接到数据库,然后选择。
  • 那么你的root密码是root吗?您可以从哪里以 root 身份登录。
  • 我只能从 localhost 以 root 身份登录,但是是的,我的密码是 root。

标签: javascript mysql node.js database-connection


【解决方案1】:

你需要设置socketPath

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

});

【讨论】:

    【解决方案2】:

    我不得不修改mysql配置文件。我注释掉了skip-networking,它解决了我的问题。

    如果有人能解释我为什么这么好,我会感谢它。

    【讨论】:

    • Node-mysql 默认假定 localhost:3306。使用 skip-networking mysql 仅使用 unix 套接字(使用 mysqladmin variables | grep sock 查找位置),mysql-client 可以连接到该套接字,而节点代码不能(它不知道位置)。使用socketPath 指定套接字路径并取消注释skip-networking 以获得更好的mysql 性能
    【解决方案3】:

    我在 MacOSX 上使用 MAMP,记得添加这个

    “socketPath”:“/Applications/MAMP/tmp/mysql/mysql.sock”

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

    【讨论】:

      【解决方案4】:

      当你使用 node-mysql 连接到 mysql 时,你需要指定你的主机名。如果您使用的是 linux,则可以使用以下命令查找:hostname

      所以你知道,我有同样的问题,我可以通过命令行连接到 mysql 而无需指定主机名,但在节点中你需要更改它。至少在我的情况下。 (v0.4.10) 为什么?我不确定,所以也许其他人有想法。

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

      【讨论】:

        猜你喜欢
        • 2011-07-01
        • 2013-03-25
        • 1970-01-01
        • 2016-12-03
        • 2014-01-25
        • 1970-01-01
        • 2018-10-03
        • 1970-01-01
        相关资源
        最近更新 更多