node.js + mysql 连接池

2021-11-20 00:00:00 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);
         })
     })
}

这是个好方法吗?我真的找不到太多使用 mysql 连接的例子,除了非常简单的一个,所有的事情都在主 app.js 脚本中完成,所以我真的不知道什么是约定/最佳实践.

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 模块的导出部分以仅返回一个连接,这样我就不必每次都编写 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();

相关文章