Node.js MySQL integration Run a number of queries with a single connection from a pool


Example

There may be situations where you have setup a pool of MySQL connections, but you have a number of queries you would like to run in sequence:

SELECT 1;
SELECT 2;

You could just run then using pool.query as seen elsewhere, however if you only have one free connection in the pool you must wait until a connection becomes available before you can run the second query.

You can, however, retain an active connection from the pool and run as many queries as you would like using a single connection using pool.getConnection:

pool.getConnection(function (err, conn) {
  if (err) return callback(err);

  conn.query('SELECT 1 AS seq', function (err, rows) {
    if (err) throw err;

    conn.query('SELECT 2 AS seq', function (err, rows) {
      if (err) throw err;

      conn.release();
      callback();
    });
  });
});

Note: You must remember to release the connection, otherwise there is one less MySQL connection available to the rest of the pool!

For more information on pooling MySQL connections check out the MySQL docs.