python 封装sql 增删改查连接MySQL <5-1>

select * from Teacher limit 10

连接字符串配置MysqlConfig.py

class MysqlConfig:
        HOST ='192.168.56.210'
        PORT =3306
        USER ='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 MysqlConfig

class 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 res
        except Exception as e:
            raise e#打印日志
    #增删改方法
    def __do(self,sql):
        try:
            self.cursor.execute(sql)#执行SQL语句
        except Exception as e:
            self.db.rollback()#如果执行失败要回滚
            #打日志
            raise e
        else:
            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()

如何封装Python 操作MySQL 让自动化测试更轻松

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值