【接口测试】5_PyMySQL模块 _数据库工具类封装

文章目录

一、封装的目的

  • 将 数据库常用的操作,封装成类中的方法。 将来在使用时,只需提供 要执行的SQL语句,给这个方法,即可执行。
  • 使用者,不需要关心:建立连接、创建游标、关闭游标、关闭连接

二、封装实现(重点)

类方法,可以用类名直接调用,添加装饰器。

python 复制代码
类方法:create_conn()     // 获取数据库连接

类方法:close_conn()      // 关闭数据库连接

类方法:query_one(sql)    // 查询一条数据

类方法:db_uid(sql)       // 执行数据库增删改

要求:定义一个DBTools工具类,对外提供以上方法

三、搭建框架

python 复制代码
# 定义 数据库工具类
class DBTools(object):
    
    # 创建连接
    def create_conn(self):
        pass

    # 查一条记录
    def query_one(self, sql):
        pass
        # 创建连接
        # 创建游标
        # 关闭游标
        # 关闭连接

    # 增删改记录
    def db_uid(self, sql):
        pass
        # 创建连接
        # 创建游标
        # 关闭游标
        # 关闭连接

四、案例(重点)

id title pub_date read comment is_delete
1 射雕英雄传 1960-05-01 12 34 0
2 天龙八部 1966-07-24 37 40 0
3 笑傲江湖 1995-12-24 23 80 0

4.1 设置私有方法

让创建连接方法 create_conn( ) 对用户不可见(对用户没用),但是又不影响后面查询和修改方法使用。

--->设置私有方法 __create_conn( )

python 复制代码
# 定义 数据库工具类
class DBTools(object):
    # 创建连接 - 类方法。可以直接使用类名调用!
    @classmethod
    def __create_conn(cls):
        conn = pymysql.connect(host="172.16.28.4", port=3306, user="root", password="root",
                               database="books", charset="utf8")
        # 不能遗漏(创建连接之后,要返回结果)
        return conn

4.2 实现类方法

4.2.1 查询一条记录

python 复制代码
import pymysql

# 定义 数据库工具类
class DBTools(object):
    # 创建连接 - 类方法。可以直接使用类名调用!
    @classmethod
    def __create_conn(cls):
        conn = pymysql.connect(host="172.16.28.4", port=3306, user="root", password="root",
                               database="books", charset="utf8")
        # 不能遗漏(创建连接之后,要返回结果)
        return conn

# 查一条记录 - 封装为类方法,方便调用
    @classmethod
    def query_one(cls, sql):
        my_conn = None
        my_cursor = None
        res = None
        try:
            # 创建连接。借助类名,调用 类方法 create_conn。
            my_conn = DBTools.__create_conn()   # 接收 return conn返回的结果,给my_conn
 
            # 创建游标
            my_cursor = my_conn.cursor()
            # 执行 sql 语句,做查询
            my_cursor.execute(sql)
            # 提取一条记录
            res = my_cursor.fetchone()
        except Exception as err:
            print("执行查询SQL失败:", str(err))
        finally:
            # 关闭游标
            my_cursor.close()
            # 关闭连接
            my_conn.close()
            # 返回查询结果
            return res
        
        
if __name__ == '__main__':
	result = DBTools.query_one("select * from t_book;")
    print("查询语句的结果:", result)

4.2.2 增删改数据

python 复制代码
import pymysql

# 定义 数据库工具类
class DBTools(object):
    # 创建连接 - 类方法。可以直接使用类名调用!
    @classmethod
    def __create_conn(cls):
        conn = pymysql.connect(host="172.16.28.4", port=3306, user="root", password="root",
                               database="books", charset="utf8")
        # 不能遗漏
        return conn

# 增删改记录
    @classmethod
    def db_uid(cls, sql):
        my_conn = None
        my_cursor = None
        try:
            # 创建连接.
            my_conn = DBTools.__create_conn()  
            # 创建游标
            my_cursor = my_conn.cursor()
            # 执行 增删改 语句
            my_cursor.execute(sql)
            print("Affected rows:", my_conn.affected_rows())
            # 提交事务
            my_conn.commit()
        except Exception as err:
            print("执行 增删改 SQL 失败:", str(err))
            # 回滚事务
            my_conn.rollback()
        finally:
            # 关闭游标
            my_cursor.close()
            # 关闭连接
            my_conn.close() 
          
if __name__ == '__main__':
    DBTools.db_uid("update t_book set `read` = 100 where id = 3;")

4.3 完整代码实现

文件:py08_db_tools.py

python 复制代码
import pymysql

# 定义 数据库工具类
class DBTools(object):
    # 创建连接 - 类方法。可以直接使用类名调用!
    @classmethod
    def __create_conn(cls):
        conn = pymysql.connect(host="172.16.28.4", port=3306, user="root", password="root",
                               database="books", charset="utf8")
        # 不能遗漏
        return conn

    # 查一条记录 - 封装为类方法,方便调用
    @classmethod
    def query_one(cls, sql):
        my_conn = None
        my_cursor = None
        res = None
        try:
            # 创建连接, 借助类名,调用 类方法 create_conn
            my_conn = DBTools.__create_conn()
            # 创建游标
            my_cursor = my_conn.cursor()
            # 执行 sql 语句,做查询
            my_cursor.execute(sql)
            # 提取一条记录
            res = my_cursor.fetchone()
        except Exception as err:
            print("执行查询SQL失败:", str(err))
        finally:
            # 关闭游标
            my_cursor.close()
            # 关闭连接
            my_conn.close()
            # 返回查询结果
            return res

    # 增删改记录
    @classmethod
    def db_uid(cls, sql):
        my_conn = None
        my_cursor = None
        try:
            # 创建连接
            my_conn = DBTools.__create_conn()
            # 创建游标
            my_cursor = my_conn.cursor()
            # 执行 增删改 语句
            my_cursor.execute(sql)
            print("Affected rows:", my_conn.affected_rows())
            # 提交事务
            my_conn.commit()
        except Exception as err:
            print("执行 增删改 SQL 失败:", str(err))
            # 回滚事务
            my_conn.rollback()
        finally:
            # 关闭游标
            my_cursor.close()
            # 关闭连接
            my_conn.close()

if __name__ == '__main__':
    result = DBTools.query_one("select * from t_hero;")
    print("查询语句的结果:", result)

    DBTools.db_uid("update t_book set `read` = 100 where id = 3;")

五、小结

相关推荐
GBASE1 天前
G术时刻 |GBase 8s数据库事务并发控制之封锁技术介绍(下)
数据库
xiezhr1 天前
逛GitHub发现了一款免费的带AI功能的数据库管理工具
数据库·ai编程·dba
吃糖的小孩2 天前
给 QQ AI 机器人设计“可控记忆”:会话摘要、手动长期记忆与角色卡边界
数据库
笃行3503 天前
金仓数据库数据安全双防线:静态存储加密与传输加密实战
数据库
笃行3503 天前
金仓数据库物理备份实战:sys_rman 全流程演练与误覆盖抢救
数据库
笃行3503 天前
金仓数据库逻辑备份实战:从全库导出到 Schema 替换的完整闭环
数据库
SelectDB4 天前
阶跃星辰基于 SelectDB 构建 PB 级 Agent 可观测平台
大数据·数据库·aigc
这个DBA有点耶4 天前
GROUP BY优化全解:如何写出既不丢数据又飞快的分组查询
数据库·mysql·架构
掉头发的王富贵4 天前
【StarRocks】极限十分钟入门StarRocks
数据库·sql·mysql