Nodejs接続サーバとMsqlデータベースを接続する(事務機能付き)

5730 ワード

mySql Just Query.js
/**
 *     ,               
 * funcName :      ,      
 */
exports.getClient =function (funcName){
    query.pool.acquire(function(err,client){
        client.query("BEGIN;",function(err,rows,fields){
            funcName(err,client);//      。      
        })
    })
}


/**
 *       ,      
 * client :      
 * funcName :         (          ,      )
 */
exports.rollBack = function(client,res,data){
    client.query("rollBack;",function(err,rows,fields){
        query.pool.release(client);//    
        //funcName(err,res)
        if(data.render){
            var renderStr = data.render;
            delete data["render"];//      
            res.render(renderStr,data)
        }else {
            res.send(data);//       
        }
    })
}



/**
 *     :           
 * client :  
 * funcName :         (          ,      )
 */
exports.endT = function(client,res,data){
    client.query("COMMIT;",function(err,rows,fields){
        //if(err)mySql.rollBack(client,funcName,res,"       ");
        query.pool.release(client);//    
        //funcName(err,res)
        if(data.render){
            var renderStr = data.render;
            delete data["render"];
            res.render(renderStr,data);
        }else {
            res.send(data);//  
        }


    })
}


/**
 *   sql  
 * sql :    sql  
 * client :  
 * funcName :         
 */
exports.querySql = function(sql,client,funcName){
    client.query(sql,function(err,rows,fields){
        var result = {};
            result.status = "  ";
        if (err){
            result.status = "  ";
            result.err = err;
        }else{
            if(rows.insertId > -1){
                result.affectedRows = rows.affectedRows;//     
                result.changedRows = rows.changedRows;//       
                if(rows.insertId > 0)result.insertId = rows.insertId;//insert         id
            }else{
                result.data = rows;//   select     
            }
        }
        funcName(err,client,result);//result     {status:"  or  ",data:"Array Or JSON"}
    })
}
使用プロセスtest.js

//    


var mysqlT= require("../public/mySqlJustQuery.js");

module.exports.run = function(conn,body){

    mysqlT.getClient(doSql);//    

    function doSql(err,client){
        mysqlT.querySql("update user set username = 'test'",client,checkUser);
    }

    function checkUser(err,client,result){
        if(err || result.status != "  " || !result.data.length){
            mysqlT.rollBack(client,res,'{status:"  "}');//        
        }else{
            mysqlT.endT(client,res,'{status:"  "}');//  
        }
        mysqlT.querySql("update user set passWord= 'test'",client,response);
    }

    function response(err,client,result){
        if(err || result.status != "  " || !result.data.length){
            mysqlT.rollBack(client,res,'{status:"  "}');//        
        }else{
            mysqlT.endT(client,res,'{status:"  "}');//  
        }
    }
};