node-mysql似乎无法连接

时间:2014-09-21 20:43:47

标签: javascript node.js node-mysql

我一直遇到node-mysql的问题,我无法与它建立连接。这是我的代码:

var mysql = require('mysql');
var pool = mysql.createPool({
    connectionLimit: 10,
    user: 'node',
    password: 'pass',
    host: 'localhost',
    port: 3306,
    database: 'store'
});

exports.getUser = function(user, pass){
    var sql = 'SELECT * FROM store.users WHERE user = \'' + user + '\' AND password = \'' + pass + '\'';
    pool.query(sql, function(err, rows, fields) {
      if(err){
        return err;
      }else{
          return rows.length;
      }
    });
};

只是似乎无法抛出错误或任何东西。数据库中的密码是纯文本用于测试,所以如果我调用它:

var pool = require('./database');
var message = pool.getUser('test','test');

1 个答案:

答案 0 :(得分:1)

问题是你的getUser函数在数据库函数异步执行时立即返回。因此,当查询函数完成时,getUser函数早已退出。

你可以通过传递一个回调函数以及你的用户名和密码来解决这个问题,如下所示:

var mysql = require('mysql');

var pool = mysql.createPool({
    connectionLimit: 10,
    user: 'root',
    password: '',
    host: '127.0.0.1',
    port: 3306,
    database: 'store'
});

exports.getUser = function(user, pass, cb){
    var sql = 'SELECT * FROM store.users WHERE user = \'' + user + '\' AND password = \'' + pass + '\'';

    pool.getConnection(function(err, connection) {
        if(err) throw err;

        // Use the connection
        connection.query( sql, function(err, rows) {
            if(err) throw err;
            cb(rows.length);

            // And done with the connection.
            connection.release();
        });
    });

};

然后,你可以这样调用你的函数:

var pool = require('./database');
pool.getUser('someuser', '1234', function(result){ console.log(result); } );

为了处理nodejs的异步性质,我建议看看Node Nodener Book(http://www.nodebeginner.org)。甚至还有一个部分解决了你的问题,标题为"事件驱动的异步回调。"