sql.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #!/usr/bin/python3
  2. import pymysql
  3. import log
  4. import main
  5. class user_mysql(object):
  6. def __init__(self, host, username, password, database, master=None):
  7. self.host = host
  8. self.username = username
  9. self.password = password
  10. self.database = database
  11. self.db = None
  12. self.busy = False
  13. self.log_file = log.log_file
  14. self.log_print = log.log_file
  15. def connect(self):
  16. # 打开数据库连接
  17. try:
  18. self.db = pymysql.connect(host=self.host, user=self.username, password=self.password,
  19. database=self.database)
  20. return True
  21. except Exception as e:
  22. self.log_file.logger.error('mysql连接异常: {0}'.format(e), exc_info=True, stack_info=True)
  23. return False
  24. def close(self):
  25. # 关闭数据库连接
  26. try:
  27. self.db.close()
  28. return True
  29. except Exception as e:
  30. self.log_file.logger.error('mysql关闭异常: {0}'.format(e), exc_info=True, stack_info=True)
  31. return False
  32. def sql_action(self, sql):
  33. # 使用cursor()方法获取操作游标
  34. cursor = self.db.cursor()
  35. try:
  36. # 执行sql语句
  37. cursor.execute(sql)
  38. # 执行sql语句
  39. self.db.commit()
  40. return True
  41. except Exception as e:
  42. self.log_file.logger.error('mysql执行异常: {0}'.format(e), exc_info=True, stack_info=True)
  43. # 发生错误时回滚
  44. self.db.rollback()
  45. return False
  46. def sql_inquire(self, sql):
  47. # 使用cursor()方法获取操作游标
  48. cursor = self.db.cursor()
  49. try:
  50. # 使用 execute() 方法执行 SQL 查询
  51. cursor.execute(sql)
  52. # 获取所有记录列表
  53. results = cursor.fetchall()
  54. return results
  55. except Exception as e:
  56. self.log_file.logger.error('mysql查询异常: {0}'.format(e), exc_info=True, stack_info=True)
  57. # 发生错误时回滚
  58. return None
  59. def sql_inquire_all(self, sqlstr):
  60. self.busy = True
  61. self.connect()
  62. result = self.sql_inquire(sqlstr)
  63. self.close()
  64. self.busy = False
  65. return result
  66. def sql_action_all(self, sqlstr):
  67. self.busy = True
  68. self.connect()
  69. result = self.sql_action(sqlstr)
  70. self.close()
  71. self.busy = False
  72. return result
  73. sqlclient = user_mysql("localhost", "root", "1234qwer!@#$QWER", "G01_0350")