mysql_helper.py 1.9 KB

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