使用参考:https://www.yuque.com/u1046159/erg6ec/bbqe4q#RFrM9
DB.py
import pymysql
from config import host, user, password, db, charset, port
class DB():
def __init__(self):
self.host = host
self.user = user
self.password = password
self.dbName = db
self.charset = charset
self.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)
# 插入、更新、删除操作必须进行commit
self.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)
```