使用参考:https://www.yuque.com/u1046159/erg6ec/bbqe4q#RFrM9
    DB.py

    1. import pymysql
    2. from config import host, user, password, db, charset, port
    3. class DB():
    4. def __init__(self):
    5. self.host = host
    6. self.user = user
    7. self.password = password
    8. self.dbName = db
    9. self.charset = charset
    10. self.port = port
    11. # 连接数据库
    12. def connet(self):
    13. try:
    14. # 连接数据库
    15. self.conn = pymysql.connect(
    16. host=self.host,
    17. user=self.user,
    18. password=self.password,
    19. db=self.dbName,
    20. port=self.port,
    21. charset=self.charset,
    22. )
    23. # 获得游标
    24. # pymysql.cursors.DictCursor 以字典的形式返回查询出来的数据
    25. self.cursor = self.conn.cursor(pymysql.cursors.DictCursor)
    26. except Exception as e:
    27. print(str(e)) # 实际中可以写在日志中
    28. # 关闭游标、数据库
    29. def close(self):
    30. try:
    31. # 关闭游标
    32. self.cursor.close()
    33. # 关闭数据库
    34. self.conn.close()
    35. except Exception as e:
    36. print(str(e))
    37. # 查询多条数据
    38. def get_all(self, sql):
    39. try:
    40. self.connet()
    41. self.cursor.execute(sql)
    42. res = self.cursor.fetchall()
    43. self.close()
    44. except Exception as e:
    45. print(str(e))
    46. return res
    47. # 插入、更新、删除操作公共方法
    48. def edit(self, sql):
    49. try:
    50. self.connet()
    51. self.cursor.execute(sql)
    52. # 插入、更新、删除操作必须进行commit
    53. self.conn.commit()
    54. self.close()
    55. except Exception as e:
    56. print(str(e))
    57. # 数据库插入、更新、删除操作
    58. def insert(self, sql):
    59. return self.edit(sql)
    60. def update(self, sql):
    61. return self.edit(sql)
    62. def delete(self, sql):
    63. return self.edit(sql)
    • 其中数据库连接信息写在根目录下面的config.py 中
      1. host = 'localhost'
      2. user = 'root'
      3. password = ''
      4. db = 'ehsy_data'
      5. charset = 'utf8'
      6. port = 3306
      调用: ```python from pymysqlStudy.connect_mysql_impro import DB

    if name == ‘main‘: db = DB()

    1. # sql = " insert into st_info(id,name,password) values (%s,%s,%s)"
    2. # data = (11,'lisi','123456')
    3. # db.insert(sql,data)
    4. # 更新操作
    5. sql = " update st_info set name=%s where id=%s"
    6. data = ('lisi',11)
    7. db.update(sql,data)

    ```