Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 506
Miloš Rašić Avatar asked May 21 '14 12:05

Miloš Rašić


People also ask

How do I create a MySQL connection pool in node JS?

Nodejs MySQL Integration: Pool Connectionsvar pool = mysql. createPool({ connectionLimit: 7, host: 'localhost', user: 'root', password: '', database: 'todoapp' });

What is the difference between createPool and createConnection?

mysql. createPool is a place where connections get stored. When you request a connection from a pool,you will receive a connection that is not currently being used, or a new connection. If you're already at the connection limit, it will wait until a connection is available before it continues.

What is pooling in Nodejs?

The Node. js driver supports connection pooling. Connection pooling allows your application to reuse existing connections by automatically saving the connection to a pool so it can be reused, rather than repeatedly creating a new connection to the SAP HANA database server.

Is it good to use MySQL with node js?

js is coupled with MongoDB and other NoSQL databases, but Node. js performs well with relational databases like MySQL, too. If you want to write a new microservice with Node. js for an existing database, it's highly likely that you'll use MySQL, one of the world's most popular open-source databases.


1 Answers

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

like image 101
Miloš Rašić Avatar answered Sep 22 '22 14:09

Miloš Rašić