【问题标题】:"Unable to acquire a connection" when trying to query more than once尝试多次查询时“无法获取连接”
【发布时间】:2020-03-15 07:49:46
【问题描述】:

我正在我的 node.js 项目中使用 MySQL 数据库。我用 Knex 创建了一个对数据库的查询,没关系。但是当我尝试再查询一次时,我遇到了这个错误:

Error: Unable to acquire a connection
at Client_MySQL.acquireConnection 
  (C:\Users\Darek\Desktop\proj\node_modules\knex\lib\client.js:336:30)
at Runner.ensureConnection 

这是我的knexfile.js

const dotenv = require('dotenv');
dotenv.config();
module.exports = {
    client: 'mysql',
    connection: {
        host: 'localhost',
        user: process.env.MYSQL_USER,
        password: process.env.MYSQL_PASS,
        database: 'testDB'
    }
};

然后我必须重新启动我的 npm。我搜索了这个问题的解决方案,但没有适合我的解决方案。

我又看到了这个错误:

(node:8428) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

这是一个发生错误的代码。它在我的用户模型中起作用:

module.exports.check = (number) => {
  var bbb = 0;
  return knex
    .from('employ')
    .select('ID')
    .where('emp_number', '=', number)
    .then((row) => {

      bbb = row.length;
      return(bbb);
     })
    .finally(() => {
         knex.destroy();
       })



};

还有这个函数的调用:

const numberExist = await User.check(req.body.number);

【问题讨论】:

  • 嗨,德里克。您能否包含显示您连接到数据库的位置的代码?这是 Express 服务器吗?
  • 是的。是快递服务器。我编辑了我放置一些新代码的问题

标签: mysql node.js knex.js


【解决方案1】:

您不需要致电knex.destroy(),而且在大多数情况下,您可能不应该这样做。如果您有一系列测试或一次性脚本,destroy 很有用,但对于需要在请求后继续运行的服务器,您希望 Knex 管理自己的连接池。我建议删除您的 finally 块,并进一步确保您能够优雅地处理错误(使用 catch):

try {
  const numberExist = await User.check(req.body.number);
  // ... do something with numberExist ...
} catch (e) {
  console.error('Uh-oh:', e.message);
  res.status(500).json({ error: "Something unexpected happened!" });
}

另请注意,您的查询是 COUNT,因此这样做更有效:

module.exports.check = number => 
  knex('employ')
    .count('ID')
    .where('emp_number', number)

【讨论】:

  • 我删除了 '.finally' 并且有效。非常感谢!
  • 发生在我身上的问题完全相同。问题是 knex.destroy()
猜你喜欢
  • 2021-04-22
  • 2017-05-31
  • 2017-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-11
  • 2019-01-04
  • 2016-07-18
相关资源
最近更新 更多