Node.js使用MySQL连接池示例

下面是一个封装好的工具类:

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

var db_handle = {};

db_handle.execute = function (sql, callback, failCallback) {
    pool.getConnection((error,connection)=>{
        if (error) {
            failCallback && failCallback(error);
        }
        else {
            connection.query(sql, (error2, result)=>{
                if (error2) {
                    failCallback && failCallback(error2);
                }
                else {
                    callback && callback(result);
                }
                connection.release();
            });
        }
    });
}

module.exports = db_handle;

for (var i = 0; i < 10000; i ++) {
    db_handle.execute(`select ${i}+1`, (result)=>console.log('result: ' + JSON.stringify(result)), (error)=>console.log('error: ' + error));
}

2019新年祈福,希望这个db_handle能稳健的支持我的系统运行。

posted @ 2019-01-02 07:48  zifeiy  阅读(273)  评论(0编辑  收藏  举报