If you don't want the program to die or wait too long when querying data, it is generally not recommended to open a connection in node after all queries use this link and do not close. Because the MySQL in node is not like PHP in the completion of the query will be broken, as long as not active disconnection, the connection has been there, when the number of connections reached a certain number of serious congestion, there are various delays and the phenomenon of death. When the concurrency is large, the concurrency pressure can be mitigated by establishing a connection pool.
The query () method used to manipulate the data in the MySQL module in node receives different parameters and requires special attention when used. The specific modules are as follows:
/** * mysql Connection pool module * @author Jeri * @time 2016.5.24*/varMysql=require ("MySQL");/** * Connection Pool Build * @pool {object}*/varPool =Mysql.createpool ({host:' localhost ', User:' Root ', Password:‘‘, Database:' Movielens ', Port:3306 }); /** * Select and delete operations * @param {string} SQL SQL statement * @param {function} callback callback function * @return {none} */varsdquery=function(sql,callback) {pool.getconnection (function(err,conn) {if(Err) {Console.log (' CONNECT ERROR: ', Err.message); Callback (Err,NULL,NULL); }Else{conn.query (SQL,function(qerr,vals,fields) {//Release Connectionconn.release (); //Event-driven callbackscallback (Qerr,vals,fields); }); } }); }; /** * UPDATE and insert operation * @param {string} SQL SQL statement * @param {array} params parameter array * @param {Function} callb ACK Callback function * @return {none}*/varuiquery=function(sql,params,callback) {pool.getconnection (function(err,conn) {if(Err) {Console.log (' CONNECT ERROR: ', Err.message); Callback (Err,NULL,NULL); }Else{conn.query (sql,params,function(qerr,vals,fields) {//Release Connectionconn.release (); //Event-driven callbackscallback (Qerr,vals,fields); }); } }); }; /** * Query function overload * @return {None}*/varquery =function(){ varLen =arguments.length; if(len==2) { varsql = Arguments[0]; varCB = Arguments[1]; Sdquery (SQL, CB); } Else if(len = = 3){ varsql = Arguments[0]; varparams = arguments[1]; varCB = Arguments[2]; Uiquery (SQL, params, CB); } Else{Console.log (' ERROR: ', ' wrong pass '); }};//Exposed Interfacemodule.exports = query;
MySQL Connection pool module