第二个请求的node-mysql连接错误

时间:2013-09-03 13:09:29

标签: javascript mysql node.js node-mysql

当我运行像

这样的server.js时
...
var app = require('express')(), mysql = require('mysql');
var mysqlConn = mysql.createConnection(connParam);
var controllers = {mysql: require('./controller/mysql.js')(app, mysqlConn, null)};
...

和controller / mysql.js

...
module.exports = function (app, conn, data) {
...
app.get('/mysql', mysqlController);
function mysqlController (req, res, next) {
  console.log('reached mysqlController');
  conn.connect(function (err) {
    if (!err) {
      console.log('mysql connection established');
    }
    else {
      console.log('mysql connection ERROR');
    }
  });
  conn.query('select * from users', function (err, sqlRes) {
    if (!err) {
      console.log('\tdb query success from conn');
      app.render('mysql/index.jade', {title: 'App | MySql:index', result: sqlRes},
      function (err, html) {
        console.log('\trendering mysql/index');
        res.send(html);
        conn.end(function (err) {
          console.log('mysql connection closed');
        });
      });
    }
    else {
      console.log('\tError processing query from db');
      res.send("ERROR 505");
    }
  });
}

对于第一个请求,我得到了预期的结果,但第二次,它没有连接......

:~/workspace/noder$ node server.js
Server listening to port: 8080
reached mysqlController
mysql connection established
    db query success from conn
    rendering mysql/index
mysql connection closed
reached mysqlController
mysql connection ERROR
    Error processing query from db

有人可以帮助我吗...

1 个答案:

答案 0 :(得分:1)

这是因为您在已连接的连接上调用connect()。尝试在控制器/ mysql函数本身中调用connect()而不是app.get()。这样connect()只会被调用一次..

此外,如果它没有修复它,在错误的控制台日志中,也打印错误console.log('mysql error', err);