db_helper.py 820 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. import pymysql
  2. from config import set_config
  3. config_ = 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