how does createConnection work with nodeJS in mysql?

Kiss Koppány picture Kiss Koppány · Oct 20, 2016 · Viewed 15.8k times · Source

What does createConnection do?

var connection = mysql.createConnection({
  host     : 'example.org',
  user     : 'bob',
  password : 'secret'
});

I'm writing an application in nodeJS using mysql module. I have some own modules, for example authentication, which definetely needs DB connection. Question is: if I have multiple modules where I use this method to create the connection, will it create a new connection for me everytime or use the first one? If creates, it creates the first time it loads my own module or everytime? Oh, and if it creates when is it going to be destroyed?

Here's how I have it in my authentication module:

var config = require('./config.js');
var mysql = require('mysql');
var connection = mysql.createConnection(config.connectionString);

exports.login = function() ...

I have some basic understanding missings about how modules and own modules work.

Thanks for the answers.

Answer

Dave picture Dave · Oct 20, 2016

You can create a connection pool in one module and then share that pool across all your modules, calling pool.getConnection() whenever you need to. That might be better than keeping a single, shared connection open all the time.

One project I'm working on does this:

utils/database.js

var mysql = require('mysql');

var pool = mysql.createPool({
    connectionLimit: 100,
    host: 'localhost',
    user: 'xxxxx',
    password: 'yyyyy',
    database: 'zzzzz',
    debug: false
});

module.exports = pool

accounts.js

var express = require('express');
var router = express.Router();

var pool = require('./utils/database');

router.get('/', function(req, res) {

    pool.getConnection(function(err, connection) {

        // do whatever you want with your connection here

        connection.release();

    });
});

module.exports = router;

Another way I'm playing around with is like this:

utils/database.js

var mysql = require('mysql');

var pool = mysql.createPool({
    connectionLimit: 100,
    host: 'localhost',
    user: 'xxxxx',
    password: 'yyyyy',
    database: 'zzzzz',
    debug: false
});

var getConnection = function(callback) {
    pool.getConnection(function(err, connection) {
        callback(err, connection);
    });
});

module.exports = getConnection;

accounts.js

var express = require('express');
var router = express.Router();

var createConnection = require('./utils/database');

router.get('/', function(req, res) {

    createConnection(function(err, connection) {

        // do whatever you want with your connection here

        connection.release();

    });
});

module.exports = router;