The use of mysql connection pool in node.js [transfer]


The initial approach was to create a connection and then use it. Later, it was found that there would be a situation of stuck and unresponsive after a period of time. Only by restarting the nodejs service, after a search, I thought of using a connection pool. After testing, the situation of stuck and unresponsive no longer occurred. .

Reference link: https://www.npmjs.com/package/mysql http://blog.csdn.net/lovingshu/article/details/41721233

Node.js mysql connection pool module

1. Install node's mysql module npm -install -g node-mysql
2. Create a class library, let's call it mysql_pool.js, and the content is as follows:

var mysql=require("mysql");  
var pool = mysql.createPool({  
    host: 'localhost',  
    user: 'user',  
    password: 'password',  
    database: 'database',  
    port: port  
});  
  
var query=function(sql,options,callback){  
    pool.getConnection(function(err,conn){  
        if(err){  
            callback(err,null,null);  
        }else{  
            conn.query(sql,options,function(err,results,fields){  
                //释放连接  
                conn.release();  
                //事件驱动回调  
                callback(err,results,fields);  
            });  
        }  
    });  
};  
  
module.exports=query;  

3. Use the following in the js class

var query=require("./lib/mysql_pool");  
  
query("select * from table where id=?", [1], function(err,results,fields){  
    //do something  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325519630&siteId=291194637