db_helper.py 1.5 KB

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