mysqlConnection.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. const mysql = require('mysql');
  2. const dbConfig = require('../conf/database');
  3. const adminDatabasePool = mysql.createPool(dbConfig.mysql.adminDatabase);
  4. const userInfoDatabasePool = mysql.createPool(dbConfig.mysql.userInfoDatabase);
  5. const userDatabasePool = mysql.createPool(dbConfig.mysql.userDatabase);
  6. /**
  7. * 封装使用占位符的query语句
  8. * @param {*} pool
  9. * @param {string} sql
  10. * @param {*} args
  11. * @param {function} callback
  12. */
  13. function queryArgs(pool, sql, args, callback) {
  14. pool.getConnection((err, connection) => {
  15. if (err) {
  16. console.error('error connecting: ' + err.stack);
  17. callback({
  18. err: err,
  19. errInfo: '数据库连接错误,请重试'
  20. });
  21. return;
  22. }
  23. console.log('connected as id ' + connection.threadId);
  24. connection.query(sql, args, (err, results, fields) => {
  25. if (err) {
  26. callback({
  27. err: err,
  28. errInfo: '数据库连接错误,请重试'
  29. });
  30. } else {
  31. callback(err, results, fields);
  32. }
  33. //释放链接
  34. connection.release();
  35. });
  36. });
  37. }
  38. module.exports = {
  39. pool: {
  40. adminDatabasePool: adminDatabasePool,
  41. userInfoDatabasePool: userInfoDatabasePool,
  42. userDatabasePool: userDatabasePool
  43. },
  44. queryArgs: queryArgs
  45. }