使用参考:https://www.yuque.com/u1046159/erg6ec/bbqe4q#RFrM9
DB.py
import pymysqlfrom config import host, user, password, db, charset, portclass DB():def __init__(self):self.host = hostself.user = userself.password = passwordself.dbName = dbself.charset = charsetself.port = port# 连接数据库def connet(self):try:# 连接数据库self.conn = pymysql.connect(host=self.host,user=self.user,password=self.password,db=self.dbName,port=self.port,charset=self.charset,)# 获得游标# pymysql.cursors.DictCursor 以字典的形式返回查询出来的数据self.cursor = self.conn.cursor(pymysql.cursors.DictCursor)except Exception as e:print(str(e)) # 实际中可以写在日志中# 关闭游标、数据库def close(self):try:# 关闭游标self.cursor.close()# 关闭数据库self.conn.close()except Exception as e:print(str(e))# 查询多条数据def get_all(self, sql):try:self.connet()self.cursor.execute(sql)res = self.cursor.fetchall()self.close()except Exception as e:print(str(e))return res# 插入、更新、删除操作公共方法def edit(self, sql):try:self.connet()self.cursor.execute(sql)# 插入、更新、删除操作必须进行commitself.conn.commit()self.close()except Exception as e:print(str(e))# 数据库插入、更新、删除操作def insert(self, sql):return self.edit(sql)def update(self, sql):return self.edit(sql)def delete(self, sql):return self.edit(sql)
- 其中数据库连接信息写在根目录下面的config.py 中
调用: ```python from pymysqlStudy.connect_mysql_impro import DBhost = 'localhost'user = 'root'password = ''db = 'ehsy_data'charset = 'utf8'port = 3306
if name == ‘main‘: db = DB()
# sql = " insert into st_info(id,name,password) values (%s,%s,%s)"# data = (11,'lisi','123456')# db.insert(sql,data)# 更新操作sql = " update st_info set name=%s where id=%s"data = ('lisi',11)db.update(sql,data)
```
