在使用NodeJS和Express时如何创建MySQL连接池? [英] How do I create a MySQL connection pool while working with NodeJS and Express?

查看:89
本文介绍了在使用NodeJS和Express时如何创建MySQL连接池?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够创建这样的MySQL连接:

I am able to create a MySQL connection like this:

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

connection.connect();

但是我想启动一个池并在我的项目中使用它.

But I would rather like to initiate a pool and use it across my project.

推荐答案

以后只是帮助一些人,对我有用:

Just to help some one in future, this worked for me:

我创建了一个包含池的mysql连接器文件:

I created a mysql connector file containing the pool:

// Load module
var mysql = require('mysql');
// Initialize pool
var pool      =    mysql.createPool({
    connectionLimit : 10,
    host     : '127.0.0.1',
    user     : 'root',
    password : 'root',
    database : 'db_name',
    debug    :  false
});    
module.exports = pool;

稍后,您可以简单地将连接器包含在另一个文件中,将其称为manageDB.js:

Later you can simply include the connector in another file lets call it manageDB.js:

var pool = require('./mysqlConnector');

并创建了一个像这样的可调用方法:

And made a callable method like this:

exports.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;     
        });
    });
}

这篇关于在使用NodeJS和Express时如何创建MySQL连接池?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆