A
A
Alexander Ponomarev2017-07-06 09:52:24
MySQL
Alexander Ponomarev, 2017-07-06 09:52:24

How to properly make a mysql module on nodejs?

Hello, please tell me why it is impossible to make a module for mysql in such a way that it is not constantly connected in files?
Module code:

module.exports = function () {
    var mysql = require('mysql');
    var pool =    mysql.createPool({
        host: 'localhost',
        user: 'root',
        password: '',
        database: 'links'
    });
    return pool;
};

Module connection code: Request code
var pool = require("../engine/mysql.db.js");
pool.getConnection(function (err, connection) {
            var sql = 'SELECT `original_url`,`code` FROM `links` WHERE `code`="' + req.params.code+'"';
            connection.query(sql, function (error, results, fields) {
                var result = JSON.stringify(results[0]);
                res.render('index', {title: 'Express'});
            });
        })

Thanks for your help!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Valentine, 2017-07-06
@Tpona

var mysql = require('mysql');
var pool = null;
module.exports = function () {
    if (!pool) {
    pool =    mysql.createPool({
        host: 'localhost',
        user: 'root',
        password: '',
        database: 'links'
    });
    }
    return pool;
};

Maybe something like this?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question