使用mysql& node.js中的池以更干净的方式?

时间:2018-02-13 09:05:18

标签: mysql node.js connection-pooling

我想知道在node.js中使用更短或更优雅的方式来做mysql请求(使用池)

实际上这是我如何做多个请求(我简化了示例的代码,请参阅我的评论内容):

var Mysql = require('mysql');

//Creating the pool of sql connections
var Pool = Mysql.createPool({
    host: Config.database.auth.host,
    user: Config.database.auth.user,
    password: Config.database.auth.pass,
    name: Config.database.auth.name
});

//Using one of the connections available in the pool
PoolAuth.getConnection(function (e, c) {

    if (e) {

        //failed to use the connection

    } else {

        //Executing the first query
        c.query("SELECT * FROM blabla WHERE id = ?", [1], function (e, r, f) {

            //Releasing the connection, should i do that at this moment or before closing the pool ?
            c.release();


            if (e) {

                //failed to exe the query

            }
            else {

               //Executing second query
               c.query("UPDATE blabla SET  enabled = ? WHERE id= ?", [1, r[0].id], function (e, r, f) {});

            }
        });
    }
});

能够做到这样的事情会更优雅,更干净:

var query = Pool->query("SELECT * FROM blabla WHERE id=?", [0]);
if(query) {
    Pool->query("UPDATE blabla SET enabled = ? WHERE id=?", [1, query.id]);
}

(类似于我在PHP中所做的)

感谢您的帮助

0 个答案:

没有答案