mysql_helper.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. """
  2. 数据库连接及操作
  3. """
  4. import redis
  5. import pymysql
  6. import os
  7. import sys
  8. sys.path.append(os.getcwd())
  9. from application.common.log import Local
  10. from application.config.mysql_config import env_dict
  11. class MysqlHelper(object):
  12. """
  13. MySQL工具, env默认prod版本
  14. """
  15. def __init__(self, env="prod", mode='', platform='', action=''):
  16. mysql_config = env_dict[env]
  17. self.connection = pymysql.connect(
  18. host=mysql_config['host'], # 数据库IP地址,内网地址
  19. port=mysql_config['port'], # 端口号
  20. user=mysql_config['user'], # mysql用户名
  21. passwd=mysql_config['passwd'], # mysql用户登录密码
  22. db=mysql_config['db'], # 数据库名
  23. charset=mysql_config['charset'] # 如果数据库里面的文本是utf8编码的,charset指定是utf8
  24. )
  25. self.mode = mode
  26. self.platform = platform
  27. self.action = action
  28. def select(self, sql):
  29. """
  30. 查询
  31. :param sql:
  32. :return:
  33. """
  34. cursor = self.connection.cursor()
  35. cursor.execute(sql)
  36. data = cursor.fetchall()
  37. return data
  38. def select_params(self, sql, params=None):
  39. cursor = self.connection.cursor()
  40. cursor.execute(sql, params or ()) # 支持参数化查询
  41. data = cursor.fetchall()
  42. return data
  43. def update(self, sql):
  44. """
  45. 插入
  46. :param sql:
  47. :return:
  48. """
  49. cursor = self.connection.cursor()
  50. try:
  51. res = cursor.execute(sql)
  52. self.connection.commit()
  53. return res
  54. except Exception as e:
  55. Local.logger(self.mode, self.platform).error(f"update_values异常,进行回滚操作:{e}\n")
  56. self.connection.rollback()
  57. def close(self):
  58. """
  59. 关闭连接
  60. """
  61. self.connection.close()