18

The documentation states that you can either use the pool directly with:

pool.query();

or get a connection manually and then run a query:

pool.getConnection(function(err, connection) {
  // Use the connection
  connection.query( 'SELECT something FROM sometable', function(err, rows) {
    // And done with the connection.
    connection.release();

    // Don't use the connection here, it has been returned to the pool.
  });
});

The second option is a lot of code that has to be repeated every time you need to run a query. Is it safe to just use the pool directly? Does pool.query() release the connection back into the pool when it's done?

Miloš Rašić
  • 2,229
  • 5
  • 24
  • 43

1 Answers1

20

Question kindly answered by developer on github: https://github.com/felixge/node-mysql/issues/857#issuecomment-47382419

Is it safe to just use the pool directly?

Yes, as long as you are doing single statement queries. The only reason you couldn't use that in your example above is because you are making multiple queries that need to be done in sequential order on the same connection. Calling pool.query() may be different connections each time, so things like FOUND_ROWS() will not work as you intended if the connection is not the same as the one that did the SQL_CALC_FOUND_ROWS query. Using the long method allows you to hold onto the same connection for all your queries.

Does pool.query() release the connection back into the pool when it's done?

Yes

maligree
  • 5,939
  • 10
  • 34
  • 51
Miloš Rašić
  • 2,229
  • 5
  • 24
  • 43
  • According to this answer and the [documents](https://www.npmjs.com/package/mysql#pooling-connections), `pool.query()` is equivalant to getting a connection from the pool, executing a query with it, and then releasing it, but as I tested these two methods for executing a simple `SELECT` query, there was a considerable exec time difference between them, 500 ms in my case. Is this normal or am I doing something wrong? – Galiold May 12 '20 at 21:53
  • @Galiold, I notice the same performance hit in getting a pool connection. Seems to take a minimum of 20ms, sometimes much more for me. – Peter Fernandes Apr 11 '21 at 14:16