Skip to content

Instantly share code, notes, and snippets.

@chrisl8
Last active September 17, 2015 16:05
Show Gist options
  • Save chrisl8/26e2719a675f1241e79c to your computer and use it in GitHub Desktop.
Save chrisl8/26e2719a675f1241e79c to your computer and use it in GitHub Desktop.
SQl Pool in Node.js
var sqlTable = require('./sqlTable');
function insertIntSqlTable(aThing) {
'use strict';
sqlTable.pool.query('INSERT INTO aTable (things) VALUES (?)', [aThing], function(err, rows, fields) {
if (err) console.log('SQL Error: ' + err);
});
}
var mysql = require('mysql');
var dbConnectInformation = {
connectionLimit: 10, // Just to curb our enthusiasm.
host: 'localhost',
user: '<username>',
password: '<password>',
database: '<dtabase>',
port: <portNumber>
};
var pool = mysql.createPool(dbConnectInformation);
exports.pool = pool;
@chrisl8
Copy link
Author

chrisl8 commented Sep 17, 2015

Declaring pool above the getDbConnection function allows all users of this module to share the same pool.

@chrisl8
Copy link
Author

chrisl8 commented Sep 17, 2015

Actually there is no reason not to just define the pool at creation time.
The node-mysql module will not actually connect to the DB until a query is made,
and if the DB kills off the connections, the node-mysql module will rebuild the connections
as needed up until the connection limit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment