db_helper.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #!/usr/bin/python3.6
  2. # -*- coding: utf-8 -*-
  3. # @Author : lijunliang
  4. # @Email : lijunliang@topnet.net.cn
  5. # @File : db_helper.py
  6. # @Software: PyCharm
  7. import pymysql
  8. from loguru import logger
  9. class DBHelper(object):
  10. def __init__(self, config):
  11. self.__host = config.get("host", "")
  12. self.__port = int(config.get("port", ""))
  13. self.__user = config.get("user", "")
  14. self.__password = config.get("password", "")
  15. self.__db = config.get("db", "")
  16. self.__charset = config.get("charset", "")
  17. self.link_db()
  18. def link_db(self):
  19. self.db = pymysql.connect(host=self.__host, user=self.__user,
  20. password=self.__password, db=self.__db,
  21. port=self.__port, charset=self.__charset)
  22. def execute_sql(self, sql: str):
  23. try:
  24. with self.db.cursor() as cursor:
  25. cursor.execute(sql)
  26. self.db.commit()
  27. return True
  28. except Exception as e:
  29. self.db.rollback()
  30. logger.warning("{}-->执行失败-->{}".format(sql, e))
  31. return False
  32. def search(self, sql: str):
  33. '''
  34. 执行sql搜索
  35. :param sql:
  36. :return:
  37. '''
  38. with self.db.cursor() as cursor:
  39. cursor.execute(sql)
  40. s_ret = cursor.fetchall()
  41. return s_ret
  42. def close(self):
  43. self.db.close()
  44. def create_update_sql():
  45. update = r"UPDATE files SET category = 'dog' WHERE id=1"
  46. def create_delete_sql():
  47. delte = """DELETE FROM files WHERE ID =1"""
  48. if __name__ == '__main__':
  49. from module.read_config import read_ini
  50. import datetime
  51. config = read_ini("../data/config.ini")
  52. print(config)
  53. db = DBHelper(config["mysql_config"])
  54. sql = r'select * from files where id=1'
  55. update = r"UPDATE files SET category = 'dog' WHERE id=1"
  56. delte = """DELETE FROM files WHERE ID =1"""
  57. # db.search(sql)
  58. db.execute_sql(delte)