无法在节点js中连接mysql

时间:2016-04-04 07:29:38

标签: mysql node.js

my script is here
var mysql= require('mysql');
var connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '12345',
  database: 'mydb'
});

connection.connect(function(err) {
  if (err) {
    console.error('error connecting: ' + err.stack);
    return;
  }

 console.log('connected as id ' + connection.threadId);
});

当我运行此代码时,它显示此错误

error connecting: Error: connect ETIMEDOUT
    at Connection._handleConnectTimeout (~/node_modules/mysql/lib/Connection.js:414:13)
    at Socket.g (events.js:180:16)
    at Socket.EventEmitter.emit (events.js:92:17)
    at Socket._onTimeout (net.js:327:8)
    at Timer.unrefTimeout [as ontimeout] (timers.js:412:13)
    --------------------
    at Protocol._enqueue (~/mysql/lib/protocol/Protocol.js:141:48)
    at Protocol.handshake (~/node_modules/mysql/lib/protocol/Protocol.js:52:41)
    at Connection.connect (~/node_modules/mysql/lib/Connection.js:125:18)
    at Object.<anonymous> (~/Desktop/Node-Eclipse/server.js:10:12)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)

用户名和密码以及所有其他详细信息都是正确的

2 个答案:

答案 0 :(得分:0)

我使用的导出功能与您的功能完全相同,而且运行正常。

var mysql = require("mysql");
var self = module.exports = {

    db:{},
    init: function(login, callback) {
        self.db = mysql.createConnection({
            host:'myHost',
            user:'myUser',
            password:'myPassword',
            database:'myDbName'
        });
        return self.db.connect(function(err) {
            if (err) {
                callback(null);
            }
            else {
                callback(self.db);
            }
        });
    },
    execute:function(login, request, callback) {
        return self.db.query(request, function(err, rows, fields) {
            if (err) {
                callback(null);
            }
            else {
                callback(rows);
            }
        });
    }
};

答案 1 :(得分:0)

请在您的mysql连接中传递3306的端口号