节点MySQL - 可重用的连接模块

时间:2014-03-06 23:57:34

标签: javascript mysql node.js database-connection node-mysql

问题更新:


解决方案应详细说明节点连接模块的简化,正确模型,允许节点应用程序的任何模块重新使用连接,这些模块需要连接到数据库。这样,问题可能对Node中有连接模块问题的任何人都有用。

答案甚至可能包括一种传递不同凭据的方法,以便通过应用程序中的任何位置通过单个函数调用连接到不同的表或数据库。


我写了一个脚本,它使用了许多简单的模块,允许用户发布登录数据,在服务器上验证数据,如果正确,则收到成功的响应。一个非常基本的登录功能。

问题:一个用户可以登录,但在重新启动服务器之前再次登录尝试无法连接到数据库。

看起来,因为我在模块db_connect中的变量中声明了连接并且需要该模块,所以无法重新使用该连接。它在所需的模块中声明,我错误地认为在每次连接尝试中调用变量会重新创建连接。它没有。

解决方案:正如barry在评论中所建议的那样,在db_connect模块中,我需要将连接功能变为函数而不是变量,这样我就可以在我的内部创建连接验证脚本。

我该怎么做?我正在尝试在调用createConnection()函数时输出连接对象,这是db_connect的导出方法。

db_connect:

console.log('db_connect module initialized');
var mysql      = require('mysql');

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

exports.createConnection = createConnection();
exports.mysql = mysql;

验证

console.log('validator module initialized');
var connect = require("./db_connect");

function validate(username, password, callback){

    var createConnection = connect.createConnection();
    //the idea is for this to return the object, connection, 
    //which opens a new connection

    connection.connect(function (err){
        if (err) return callback(new Error('Failed to connect'), null);
        console.log('Connection with the Officeball MySQL database openned...');

        connection.query('select username,password,fname,lname,rank,active from users where username=?',
                username,
                function(err,rows,fields) {
                    connection.destroy();
                    console.log('...Connection with the Officeball MySQL database closed.');
                    if (err)
                        return callback(new Error ('Error while performing query'), null);
                    if (rows.length !== 1)
                        return callback(new Error ('- [Anomaly] - Failed to find exactly one user'), null);

                    if (rows[0].password === password & rows[0].active === "yes") {

                        var result = new Object;

                        result.username = rows[0].username;
                        result.password = rows[0].password;
                        result.fname = rows[0].fname;
                        result.lname = rows[0].lname;
                        result.rank = rows[0].rank;

                        return callback(null, result);

                    } if(rows[0].active !== "yes"){

                        return callback(new Error ('User account not active.'), null);

                    }else {

                        return callback(new Error ('Login credentials did not match.'), null);

                    }

                });


    });
};

exports.validate = validate;

控制台日志 (最初出现连接错误,但在我的修复尝试之后,错误与方法有关)

C:\xampp\htdocs\officeball\node_scripts>node index.js
application initialized
server module initialized
login module initialized
validator module initialized
db_connect module initialized
sale module initialized
Server running at http://127.0.0.1:8080/
User username1 is attempting login...
TypeError: Property 'createConnection' of object #<Object> is not a function
    at Object.validate (C:\xampp\htdocs\officeball\node_scripts\custom_modules\v
alidator.js:6:33)
    at C:\xampp\htdocs\officeball\node_scripts\custom_modules\login.js:61:13
    at callbacks (C:\xampp\htdocs\officeball\node_scripts\node_modules\express\l
ib\router\index.js:164:37)
    at param (C:\xampp\htdocs\officeball\node_scripts\node_modules\express\lib\r
outer\index.js:138:11)
    at pass (C:\xampp\htdocs\officeball\node_scripts\node_modules\express\lib\ro
uter\index.js:145:5)
    at Router._dispatch (C:\xampp\htdocs\officeball\node_scripts\node_modules\ex
press\lib\router\index.js:173:5)
    at Object.router (C:\xampp\htdocs\officeball\node_scripts\node_modules\expre
ss\lib\router\index.js:33:10)
    at next (C:\xampp\htdocs\officeball\node_scripts\node_modules\express\node_m
odules\connect\lib\proto.js:193:15)
    at multipart (C:\xampp\htdocs\officeball\node_scripts\node_modules\express\n
ode_modules\connect\lib\middleware\multipart.js:93:27)
    at C:\xampp\htdocs\officeball\node_scripts\node_modules\express\node_modules
\connect\lib\middleware\bodyParser.js:64:9

2 个答案:

答案 0 :(得分:0)

你的问题主要是我在评论中提到的,所以我会把它作为答案。不要伤到自己拍打前额。 :-)请参阅下面的内联评论。你有一个方法调用太多,一个未返回的结果,一个错误的变量 - 否则,它的工作正常。

<强> db_connect.js

console.log('db_connect module initialized');
var mysql      = require('mysql');

function createConnection(){
    var connection = mysql.createConnection({
        host     : 'localhost',
        user     : 'root',
        password : '',
        database : 'officeball'
    });
    // ************ NOTE BELOW FOR CHANGE **************
    // You didn't return anything from this function. You need to return the connection
    return connection;
}
// ************ NOTE BELOW FOR CHANGE **************
// You are exporting a single connection by invoking createConnection();
// exports.createConnection = createConnection();
// what you want is:
exports.createConnection = createConnection;
exports.mysql = mysql;

<强> validator.js

function validate(username, password, callback){
    // ************ NOTE BELOW FOR CHANGE **************
    // You had:
    // var createConnection = connect.createConnection();
    // but based on your code, you wanted to write this instead:
    var connection = connect.createConnection();

    /// ... REMAINDER OMITTED, because it was A-OK and this is already a long page
};

如果你进行了两次三次更改,你应该好好去。与以往一样,如果有帮助,请随时要求澄清。

更新这就是我调用它的方式 - 正如您所看到的,我曾尝试过2秒钟。

<强> JT-test.js

var v = require('./validator');
var timers = require('timers');
var connections = 0;

timers.setInterval(function(){
    v.validate('bagehot','foo',function(err,result){
        if (err)
            console.log('failed', err);
        else
            console.log('success! ',result);
    });
},2000);

<强>结果

Connection with the Officeball MySQL database openned...
...Connection with the Officeball MySQL database closed.
success!  { username: 'bagehot',
  password: 'foo',
  fname: 'walter',
  lname: 'bagehot',
  rank: 12 }
Connection with the Officeball MySQL database openned...
...Connection with the Officeball MySQL database closed.
success!  { username: 'bagehot',
  password: 'foo',
  fname: 'walter',
  lname: 'bagehot',
  rank: 12 }
Connection with the Officeball MySQL database openned...
...Connection with the Officeball MySQL database closed.
success!  { username: 'bagehot',
  password: 'foo',
  fname: 'walter',
  lname: 'bagehot',
  rank: 12 }
Connection with the Officeball MySQL database openned...
...Connection with the Officeball MySQL database closed.
success!  { username: 'bagehot',
  password: 'foo',
  fname: 'walter',
  lname: 'bagehot',
  rank: 12 }

等等。它无限期地运行。这三个文件的完整代码位于this gist

答案 1 :(得分:0)

您可以查看我的emysql包裹。

https://www.npmjs.org/package/emysql

https://github.com/yanke-guo/enhanced-mysql-pool

可能它是某种过时的最新node-mysql包,但仍然有效。