1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- //参数
- var us = {
- mysql: require('mysql'),
- sqle: {}
- };
- //连接数据库
- us.mysqlconnection = function (host, database) {
- if (!us.sqle[host] || !us.sqle[host][database]) { //配置数据库连接
- us.sqle[host] = us.sqle[host] || {};
- us.sqle[host][database] = us.mysql.createPool({
- connectionLimit: 0,
- acquireTimeout: 60000,
- host: host, //数据库地址
- user: "root", //用户名
- password: "cocorobo", //密码
- database: database, //数据库名称
- port: 3306 //端口
- }); //连接超时和错误从连
- }
- //connectionLimit: 1000,
- return us.sqle[host][database]; //返回连接对象
- }
- //连接数据库调用
- exports.usselect = function (param, callback) {
- if (param.length > 1) {
- var _mysqlconnection = us.mysqlconnection(param[0], param[1]); //创建连接池
- console.log(param);
- _mysqlconnection.getConnection(function (error, connection) { //获取连接
- if (error) { //连接错误
- console.error("连接失败:", error);
- } else { //连接成功
- var _sql = "CALL ";
- var _param = new Array();
- if (param.length > 3) { //带有参数的sql语句 如:'call test(?, ?, ?);'
- _param = param.slice(3) //截取有效参数
- _sql += (param[2] || "") + "(?"; //拼接存储过程名称
- _sql += Array(_param.length).join(",?");
- _sql += ");"; //拼接结果语句
- } else { //不带参数的sql语句 如:'call test();'
- _sql += param[2] + "();";
- }
- console.log("拼凑的MySQl语句为:", _sql);
- connection.query(_sql, _param, function (error, results, fields) { //执行sql语句
- if (results) {
- callback(results.affectedRows != null ? results.affectedRows : results.length > 1 ? results : results[0]);
- }
- else { //执行错误
- console.error("sql执行失败", error || "");
- callback(error);
- }
- });
- connection.release(function (error) { //释放资源
- if (error) console.log("连接释放错误", error);
- });
- }
- });
- }
- }
- //重新连接处理
- // us.mysqlconnet.reconnection = function (host, database, error) {
- // if (error) {
- // console.log("连接失败,尝试重连", error);
- // setTimeout(function () {
- // us.mysqlconnection(host, database)
- // }, 2000);
- // }
- // }
|