|

How to connect to MySQL / MariaDB using Node.JS (the right way)

Use a connection pool. It helps

  • Conserve resource, connections got recycled
  • Better reliability: it automatically reconnects when there’s a problem

How? Simple, instead of creating a connection, just create a pool. It’s designed as a drop in replacement for client.query()

var mysql = require('mysql');
var pool  = mysql.createPool({
  connectionLimit : 10,
  host            : 'example.org',
  user            : 'bob',
  password        : 'secret',
  database        : 'my_db'
});

pool.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
  if (error) throw error;
  console.log('The solution is: ', results[0].solution);
});

is a shorthand for

var mysql = require('mysql');
var pool  = mysql.createPool(...);

pool.getConnection(function(err, connection) {
  if (err) throw err; // not connected!

  // Use the connection
  connection.query('SELECT something FROM sometable', function (error, results, fields) {
    // When done with the connection, release it.
    connection.release();

    // Handle error after the release.
    if (error) throw error;

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

Leave a Reply

Your email address will not be published. Required fields are marked *