Difference between using getConnection() and using pool directly in node.js with node-mysql module?

不问归期 提交于 2019-12-03 08:58:55

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/23783571/difference-between-using-getconnection-and-using-pool-directly-in-node-js-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!