select * from Teacher limit 10
连接字符串配置MysqlConfig.py
class MysqlConfig:HOST ='192.168.56.210'PORT =3306USER ='root'PASSWORD ='1qaz@0987654321'DB='StudentDB'CHARSET ='utf8'
封装增删改查MysqlConnection.py
'''
Author: tkhywang 2810248865@qq.com
Date: 2023-06-19 15:44:48
LastEditors: tkhywang 2810248865@qq.com
LastEditTime: 2023-08-04 07:32:36
FilePath: \projectBase\dmlmysql\MysqlConnection.py
Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
'''import pymysql
from mysqlConfig import MysqlConfigclass MysqlConnection:def __init__(self,host=MysqlConfig.HOST,port=MysqlConfig.PORT,user=MysqlConfig.USER,pwd=MysqlConfig.PASSWORD,db=MysqlConfig.DB):self.db = pymysql.connect(host=host,port=port,user=user,password=pwd,database=db,charset=MysqlConfig.CHARSET)#创建连接self.cursor = self.db.cursor()#创建游标#查询方法def query(self,sql,many=True):try:self.cursor.execute(sql)#执行SQL语句if many:res = self.cursor.fetchall()else:res = self.cursor.fetchone()return resexcept Exception as e:raise e#打印日志#增删改方法def __do(self,sql):try:self.cursor.execute(sql)#执行SQL语句except Exception as e:self.db.rollback()#如果执行失败要回滚#打日志raise eelse:self.db.commit()#提交def update(self,sql):self.__do(sql)def insert(self,sql):self.__do(sql)def delete(self,sql):self.__do(sql)def exit(self):self.cursor.close()#关闭游标self.db.close()#关闭数据库if __name__ == '__main__':db = MysqlConnection()res = db.query('select * from Teacher limit 10;') #可动态传增删改查语句print(res)db.exit()