db_helper.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import pymysql
  2. from config import set_config
  3. from log import Log
  4. config_, env = set_config()
  5. log_ = Log()
  6. class MysqlHelper(object):
  7. def __init__(self):
  8. """
  9. 初始化mysql连接信息
  10. """
  11. self.mysql_info = config_.MYSQL_INFO
  12. def get_data(self, sql):
  13. """
  14. 查询数据
  15. :param sql: sql语句
  16. :return: data
  17. """
  18. # 连接数据库
  19. conn = pymysql.connect(**self.mysql_info)
  20. # 创建游标
  21. cursor = conn.cursor()
  22. try:
  23. # 执行SQL语句
  24. cursor.execute(sql)
  25. # 获取查询的所有记录
  26. data = cursor.fetchall()
  27. except Exception as e:
  28. return None
  29. # 关闭游标对象
  30. cursor.close()
  31. # 关闭数据库连接
  32. conn.close()
  33. return data
  34. def add_data(self, sql):
  35. """
  36. 新增数据
  37. :param sql:
  38. :return:
  39. """
  40. # 连接数据库
  41. conn = pymysql.connect(**self.mysql_info)
  42. # 创建游标
  43. cursor = conn.cursor()
  44. try:
  45. # 执行SQL语句
  46. cursor.execute(sql)
  47. # 提交到数据库执行
  48. conn.commit()
  49. except Exception as e:
  50. # 发生错误时回滚
  51. log_.error(e)
  52. conn.rollback()
  53. # 关闭游标对象
  54. cursor.close()
  55. # 关闭数据库连接
  56. conn.close()
  57. if __name__ == '__main__':
  58. mysql_helper = MysqlHelper()
  59. sql = "select * from hot_word;"
  60. data = mysql_helper.get_data(sql=sql)
  61. print(data)