node.js + mysql连接池 [英] node.js + mysql connection pooling

查看:44
本文介绍了node.js + mysql连接池的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何构造应用程序以最有效地使用MySQL.我正在使用node-mysql模块.这里的其他线程建议使用连接池,因此我设置了一个小模块mysql.js

I'm trying to figure out how to structure my application to use MySQL most efficent way. I'm using node-mysql module. Other threads here suggested to use connection pooling so i set up a little module mysql.js

var mysql = require('mysql');

var pool  = mysql.createPool({
    host     : 'localhost',
    user     : 'root',
    password : 'root',
    database : 'guess'
});

exports.pool = pool;

现在,每当我要查询mysql时,我都需要此模块,然后查询数据库

Now whenever I want to query mysql I require this module and then query the databse

var mysql = require('../db/mysql').pool;

var test = function(req, res) {
     mysql.getConnection(function(err, conn){
         conn.query("select * from users", function(err, rows) {
              res.json(rows);
         })
     })
}

这是好方法吗?除了非常简单的示例(其中所有操作均在主app.js脚本中完成)之外,我真的找不到太多的使用mysql连接的示例,因此我真的不知道约定/最佳实践是什么.

Is this good approach? I couldn't really find too much examples of using mysql connections besides very simple one where everything is done in main app.js script so I don't really know what the convention / best practices are.

是否应该在每次查询后始终使用connection.end()?如果我忘了某个地方怎么办?

Should I always use connection.end() after each query? What if I forget about it somewhere?

如何重写mysql模块的exports部分以仅返回连接,这样我就不必每次都写getConnection()了?

How to rewrite the exports part of my mysql module to return just a connection so I don't have to write getConnection() every time?

推荐答案

这是一个很好的方法.

如果只想建立连接,则将以下代码添加到池所在的模块中:

If you just want to get a connection add the following code to your module where the pool is in:

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

module.exports = getConnection;

您仍然每次都必须编写getConnection.但是您可以在第一次获得连接时将其保存在模块中.

You still have to write getConnection every time. But you could save the connection in the module the first time you get it.

使用完毕后,别忘了终止连接:

Don't forget to end the connection when you are done using it:

connection.release();

这篇关于node.js + mysql连接池的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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