node.js + mysql 连接池

node.js + mysql connection pooling(node.js + mysql 连接池)
本文介绍了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();

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)
SQL/MySQL: split a quantity value into multiple rows by date(SQL/MySQL:按日期将数量值拆分为多行)