Reference: Connection Pooling

https://www.youtube.com/watch?v=2DuwaysT-nM

 

Introduction to database connection pooling.

  • Connection can do one thing at a time

 

Problem

Creating and destroying is expensive.

 

var mysql = require('mysql')
var connection = mysql.createConnection({
  host: 'localhost',
  user: 'me',
  password: 'secret',
  database: 'my_db'
  debug: false
})

connection.connect()

 

Solution

Use a pool of reusable connections

 

// mysql_connector.js

var mysql = require('mysql')

var pool = mysql.createPool({
  connectionLimit: 10,
  host: 'localhost',
  user: 'root',
  password: 'secret',
  database: 'db_name',
  debug: false
})

module.exports = pool

 

// manageDB.js

const executeQuery = function( query, callback ) {
   pool.getConnection( function(err, connection ) {
      if (err) {
          connection.release();
          throw err
      }

      connection.query( query, function( err, rows ) {
          connection.release();


          if (!err) {
              callback( null, {rows: rows} )
          }
      }


       connection.on('error', function(err) {
          throw err;
          return;
       }
   }

}

module.exports = executeQuery

 


Cursor is a pointer that travels through a resultSet

 

A tuple is a row of data in a resultSet.