mysql.js 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. //参数
  2. var us = {
  3. mysql: require('mysql'),
  4. sqle: {}
  5. };
  6. //连接数据库
  7. us.mysqlconnection = function (host, database) {
  8. if (!us.sqle[host] || !us.sqle[host][database]) { //配置数据库连接
  9. us.sqle[host] = us.sqle[host] || {};
  10. us.sqle[host][database] = us.mysql.createPool({
  11. connectionLimit: 0,
  12. acquireTimeout: 60000,
  13. host: host, //数据库地址
  14. user: "root", //用户名
  15. password: "cocorobo", //密码
  16. database: database, //数据库名称
  17. port: 3306 //端口
  18. }); //连接超时和错误从连
  19. }
  20. //connectionLimit: 1000,
  21. return us.sqle[host][database]; //返回连接对象
  22. }
  23. //连接数据库调用
  24. exports.usselect = function (param, callback) {
  25. if (param.length > 1) {
  26. var _mysqlconnection = us.mysqlconnection(param[0], param[1]); //创建连接池
  27. console.log(param);
  28. _mysqlconnection.getConnection(function (error, connection) { //获取连接
  29. if (error) { //连接错误
  30. console.error("连接失败:", error);
  31. } else { //连接成功
  32. var _sql = "CALL ";
  33. var _param = new Array();
  34. if (param.length > 3) { //带有参数的sql语句 如:'call test(?, ?, ?);'
  35. _param = param.slice(3) //截取有效参数
  36. _sql += (param[2] || "") + "(?"; //拼接存储过程名称
  37. _sql += Array(_param.length).join(",?");
  38. _sql += ");"; //拼接结果语句
  39. } else { //不带参数的sql语句 如:'call test();'
  40. _sql += param[2] + "();";
  41. }
  42. console.log("拼凑的MySQl语句为:", _sql);
  43. connection.query(_sql, _param, function (error, results, fields) { //执行sql语句
  44. if (results) {
  45. callback(results.affectedRows != null ? results.affectedRows : results.length > 1 ? results : results[0]);
  46. }
  47. else { //执行错误
  48. console.error("sql执行失败", error || "");
  49. callback(error);
  50. }
  51. });
  52. connection.release(function (error) { //释放资源
  53. if (error) console.log("连接释放错误", error);
  54. });
  55. }
  56. });
  57. }
  58. }
  59. //重新连接处理
  60. // us.mysqlconnet.reconnection = function (host, database, error) {
  61. // if (error) {
  62. // console.log("连接失败,尝试重连", error);
  63. // setTimeout(function () {
  64. // us.mysqlconnection(host, database)
  65. // }, 2000);
  66. // }
  67. // }