Darek N
Darek N

Reputation: 51

"Unable to acquire a connection" when trying to query more than once

I'm working with a MySQL database in my node.js project. I created a query with Knex to the database and it's ok. But when I try to query one more time, I have this error:

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 

This is my 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'
    }
};

Then I must restart my npm. I searched for a solution to this problem but there's no working answers for me.

I saw this error another:

(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.

Here is a code, where error occurs. It's function in my user model:

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();
       })



};

And there is a call of this func:

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

Upvotes: 4

Views: 4556

Answers (1)

Rich Churcher
Rich Churcher

Reputation: 7654

You don't need to call knex.destroy() and for the most part, you probably shouldn't. destroy is useful if you have a series of tests or a one-off script, but for a server that needs to keep running for request after request, you want Knex to manage its own pool of connections. I suggest removing your finally block, and further making certain you handle errors gracefully (using 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!" });
}

Note also that your query is a COUNT, so it's more efficient to do it this way:

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

Upvotes: 8

Related Questions