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

导读:本篇文章讲解 封装篇—Python自动化测试之封装数据库Mysql,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

一、前期准备

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'))

打印结果:读取出来了

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

 

 

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)

 运行结果:成功读取!

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

 

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/114914.html

(0)
Java光头强的头像Java光头强

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!