mysql - 错误: Cannot enqueue Handshake after already enqueuing a Handshake from nodejs application

标签 mysql node.js

我每 5 秒查询一个表并向用户显示。我使用的是mysql 8。应用程序是nodejs。

var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: xxxxxx,
  database: "test"
});


app.get('/users', (req, res) => {
  con.connect(function(err) {
  if (err) throw err;
     con.query(" select * fron table1; ",function (err, result, fields) {
if (err) throw err;
    console.log(result);
        if (result.length > 0) {
        res.send(result);
      } else {
        res.send({});
          }
  });

  });

当我再次调用该函数时,它给出了错误。 这是因为我看到我没有关闭连接。如果我尝试关闭连接,它也不起作用。 我尝试了 con.close()。 有什么办法可以让我摆脱这个

最佳答案

我认为使用池是最好的方法,我通过使用连接池并删除 .connect().end() 来修复此错误,使用 .release 相反,例如:

var pool        = mysql.createPool({
    connectionLimit : 10, // default = 10
    host            : 'localhost',
    user            : 'root',
    password        : '******',
    database        : 'test'
});

router.get('/users', function (req, res) {
    pool.getConnection(function (err, connection) {
        connection.query("SELECT * FROM table1", function (err, rows) {
            connection.release();
            if (err) throw err;

            console.log(rows.length);
            res.send(JSON.stringify(rows));
        });
    });
});

关于mysql - 错误: Cannot enqueue Handshake after already enqueuing a Handshake from nodejs application,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59915943/

相关文章:

mysql - 为什么我不能将它插入到 MySQL 中?

mysql - SQL - 选择超过 1 天的条目。错误 #1305 函数不存在

javascript - 服务器上的nodejs计时器

javascript - 查询中不等于的 Waterline ORM (sails.js) 条件

python - 无法在 QML TableView 中显示来自 QSqlQueryModel 的数据

php - mysql 数据库中的字符

mysql - 无法使用 nuget 在 Visual Studio 中安装 MySql.Data

node.js - MongoDB 使用 Node.js 获取集合中的文档数(计数)

javascript - 为什么当使用 Node Express 和 Backbone 获取请求时,我会得到用户集合和额外的对象?

javascript - 对象数组之间的区别