封装篇---Python自动化测试之封装数据库Mysql

一、前期准备

1.建一个common包,里面存放一些公共类方法(今天主要说数据库的操作)

   建一个config包,里面放配置文件

  Path.py 不多解释了代码如下

import os


# 获取工程路径
BASEDIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# 获取 commmon 路径
COMMONDIR = os.path.join(BASEDIR, 'common')

# 获取 config 路径
CONFDIR = os.path.join(BASEDIR, 'config')

 2.在config下新建base.ini

base.ini:[db]数据的信息集如下,主要就是数据库的host用户名和密码啥的,改成自己的。

[db]
host = localhost
port = 3306
user = root
pwd = root
database = tmp
charset = utf8
newkey = newValue

 二、开干!

1.首先在common下新建一个读取配置信息的方法,这里我po直接封装好的代码,方便后面直接调用,不可以写死!

import os
from common.Path import CONFDIR


class Config(ConfigParser):

    def __init__(self):
        """
        初始化
        将配置文件读取出来
        super().    调用父类
        """
        self.conf_name = os.path.join(CONFDIR, 'base.ini')
        super().__init__()
        super().read(self.conf_name, encoding='utf-8')

    def getAllsections(self):
        """
        :return: 返回所有的节点名称
        """
        return super().sections()

    def getOptions(self, sectioName):
        """
        :param sectioName: 节点名称
        :return: 返回节点所有的key
        """
        return super().options(sectioName)

    def getItems(self, sectioName):
        """
        :param sectioName: 节点名称
        :return: 返回节点的所有item
        """
        return super().items(sectioName)

    def getValue(self, sectioName, key):
        """
        :param sectioName: 节点的名称
        :param key: key名称
        :return: 返回sectioName下key 的value
        """
        return super().get(sectioName, key)

    def saveData(self, sectioName, key, value):
        """
        添加配置
        :param sectioName: 节点名称
        :param key: key名
        :param value: 值
        :return:
        """
        super().set(section=sectioName, option=key, value=value)
        super().write(fp=open(self.conf_name, 'w'))


myCof = Config()
print(myCof.getItems('db'))

打印结果:读取出来了

import pymysql
from common.getConfig import myCof


"""
封装mysql操作
"""


class OpeartorDB(object):
   
        def connectDB(self):
        """
        连接数据库
        :return: 返回成功失败,原因
        """
        host = myCof.getValue('db', 'host')
        port = myCof.getValue('db', 'port')
        user = myCof.getValue('db', 'user')
        pwd = myCof.getValue('db', 'pwd')
        database = myCof.getValue('db', 'database')
        charset = myCof.getValue('db', 'charset')
        try:
            self.db = pymysql.connect(host=host, port=int(port), user=user, password=pwd, database=database,
                                      charset=charset)
            return True, '连接数据成功'
        except Exception as e:
            return False, '连接数据失败【' + str(e) + '】'

    def closeDB(self):
        """
        关闭数据连接.
        :return:
        """
        self.db.close()

    def excetSql(self, enpsql):
        """
        执行sql方法,
        """
        go, result = self.connectDB()
        if go is False:
            return go, result
        try:
            cursor = self.db.cursor()
            cursor.execute(enpsql)
            res = cursor.fetchone()  
            if res is not None and 'select' in enpsql.lower():  # 判断是不是查询,
                des = cursor.description[0]
                result = dict(zip(des, res))  # 将返回数据格式化成JSON串
            elif res is None and ('insert' in enpsql.lower() or 'update' in enpsql.lower()):  # 判断是不是插入或者更新数据
                self.db.commit()  # 提交数据操作
                result = ''  # 操作数据,不需要返回数据
            cursor.close()  # 关闭游标
            self.closeDB()  # 关闭数据连接
            return True, result
        except Exception as e:
            return False, 'SQL执行失败,原因:[' + str(e) + ']'



sql = 'SELECT * FROM stu'
oper = OpeartorDB()
go, result = oper.excetSql(sql)
print(result)

 运行结果:成功读取!

猜你喜欢

转载自blog.csdn.net/wuyomhchang/article/details/129043078
今日推荐