How to provide a mysql database connection in single file in nodejs

前端 未结 6 627
一整个雨季
一整个雨季 2020-12-04 08:42

I need to provide the mysql connection for modules. I have a code like this.

var express = require(\'express\'),
app = express(),
server = require(\'http\').         


        
6条回答
  •  南方客
    南方客 (楼主)
    2020-12-04 09:23

    From the node.js documentation, "To have a module execute code multiple times, export a function, and call that function", you could use node.js module.export and have a single file to manage the db connections.You can find more at Node.js documentation. Let's say db.js file be like:

        const mysql = require('mysql');
    
        var connection;
    
        module.exports = {
    
        dbConnection: function () {
    
            connection = mysql.createConnection({
                host: "127.0.0.1",
                user: "Your_user",
                password: "Your_password",
                database: 'Your_bd'
            });
            connection.connect();
            return connection;
        }
    
        };
    

    Then, the file where you are going to use the connection could be like useDb.js:

    const dbConnection = require('./db');
    
    var connection;
    
    function callDb() {
    
        try {
    
            connection = dbConnectionManager.dbConnection();
    
            connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
                if (!error) {
    
                    let response = "The solution is: " + results[0].solution;
                    console.log(response);
    
                } else {
                    console.log(error);
                }
            });
            connection.end();
    
    
        } catch (err) {
            console.log(err);
        }
    }
    

提交回复
热议问题