1. MySQL

下载:pip install mysqlclientpip install pymysql
使用:import MySQLdbimport pymysql

2. 连接增删查改

3. 操作类封装

  1. from contextlib import contextmanager
  2. import pymysql
  3. import time
  4. class MySQLDB:
  5. """
  6. MySQL操作类,对MySQL数据库进行增删改查
  7. """
  8. def __init__(self, config):
  9. """
  10. 连接到数据库(保存连接信息,并连接)
  11. """
  12. self._config = config
  13. self.conn = pymysql.connect(**self._config)
  14. self.print_id()
  15. def __del__(self):
  16. """
  17. 关闭数据库连接
  18. """
  19. self.conn.close()
  20. @contextmanager
  21. def ensureConn(self):
  22. """
  23. 检查数据库是否需要重连,并在需要时重连
  24. """
  25. try:
  26. self.conn.ping(reconnect=True)
  27. except BaseException:
  28. self.conn = pymysql.connect(**self._config)
  29. yield
  30. def print_id(self):
  31. """
  32. 打印mysql连接id
  33. """
  34. with self.ensureConn():
  35. cursor = self.conn.cursor()
  36. cursor.execute("select connection_id();")
  37. res = cursor.fetchone()
  38. print("MySQLDB - mysql id: ",res)
  39. return res
  40. def excute_sql(self, sql):
  41. start = time.time()
  42. self.print_id()
  43. print("[excute_sql] start : ", sql)
  44. with self.ensureConn():
  45. cursor = self.conn.cursor()
  46. cursor.execute(sql)
  47. data = cursor.fetchall()
  48. fields = cursor.description
  49. column_list = []
  50. for i in fields:
  51. column_list.append(i[0])
  52. # print(column_list)
  53. result = []
  54. for row in data:
  55. result.append(list(row))
  56. # print(row)
  57. all_time = time.time() - start
  58. print("[excute_sql] finish - Use time : ", all_time)
  59. return result
  60. # 读权限
  61. test_config = {
  62. "host": '',
  63. "user": '',
  64. "passwd": '',
  65. "db": '',
  66. "port": ,
  67. "cursorclass": pymysql.cursors.DictCursor
  68. }
  69. Loginfo = {'user':'', 'password':'', 'host':', 'port':}
  70. # 持久连接
  71. luna_db_user = MySQLDB(Loginfo)