mysql_tools.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. # author : zhaolongyue
  4. import pymysql
  5. class Data_get():
  6. @staticmethod
  7. def connectdb(host,port,user,password,database):
  8. # print("连接到mysql服务器")
  9. db = pymysql.connect(host=host, port=port, user=user, password=password, database=database)
  10. print("数据库已连接!")
  11. return db
  12. @staticmethod
  13. def createtb(db, sql):
  14. # 使用cursor()方法获取操作游标
  15. cursor = db.cursor()
  16. # 使用 execute() 方法执行 SQL 查询
  17. cursor.execute(sql)
  18. print("数据库已创建!")
  19. # 获取mysql数据
  20. @staticmethod
  21. def insert_data(db,sql):
  22. # 使用cursor()方法获取操作游标
  23. cursor = db.cursor()
  24. # SQL语句
  25. try:
  26. # 使用 execute() 方法执行 SQL 查询
  27. cursor.execute(sql)
  28. #执行sql语句
  29. db.commit()
  30. except:
  31. #如果发生错误则回滚
  32. db.rollback()
  33. print("执行语句失败")
  34. @staticmethod
  35. def select_data(db,sql):
  36. # 使用cursor()方法获取操作游标
  37. cursor = db.cursor()
  38. # SQL语句
  39. try:
  40. # 使用 execute() 方法执行 SQL 查询
  41. cursor.execute(sql)
  42. # 执行sql语句
  43. db.commit()
  44. #获取所有记录列表
  45. results = cursor.fetchall()
  46. return results
  47. except:
  48. # 如果发生错误则回滚
  49. db.rollback()
  50. print("执行语句失败")
  51. # 关闭数据库
  52. @staticmethod
  53. def closedb(db):
  54. db.close()