# SQL数据库
import allure
import pymssql
from Utils.log import Log
logger = Log()
class Mysqldb(object):
# 初始化方法
def __init__(self, host, username, password, database):
self.host = host
self.username = username
self.password = password
self.database = database
# 初始化方法中调用连接数据库的方法
self.conn = self.get_conn()
# 调用获取游标的方法
self.cursor = self.get_cursor()
# 连接数据库的方法
def get_conn(self):
# **config代表不定长参数
try:
with allure.step(
"数据库Ip地址:{},用户名:{},密码:{},数据库名:{}".format(self.host, self.username, self.password, self.database)):
conn = pymssql.connect(host=self.host, user=self.username, password=self.password,
database=self.database)
logger.info("数据库链接成功")
return conn
except pymssql.Error as e:
logger.error("数据库连接失败,失败原因 %s" % e)
# 获取游标
def get_cursor(self):
cursor = self.conn.cursor()
return cursor
# 查询sql语句
@allure.step("数据库查询操作")
def select_one(self, sql):
try:
with allure.step("执行查询语句{}".format(sql)):
self.cursor.execute(sql)
data = self.cursor.fetchone()
logger.info("查询成功,返回查询的结果为:%s" % data)
except Exception as e:
logger.error("查询失败,失败原因 %s" % e)
return data
# 查询sql语句返回的几条数据
def select_many(self, sql, num):
self.cursor.execute(sql)
return self.cursor.fetchmany(num)
# 增删改除了SQL语句不一样其他都是一样的,都需要提交
@allure.step("数据库增删改操作")
def commit_data(self, sql):
try:
with allure.step("执行增删改语句{}".format(sql)):
# 执行语句
self.cursor.execute(sql)
# 提交
self.conn.commit()
logger.info("提交成功")
except Exception as e:
logger.info("提交失败,失败原因 %s" % e)
with allure.step("出错回滚"):
# 如果出错要回滚
self.conn.rollback()
logger.info("出错回滚")
# 当对象被销毁时,游标要关闭,连接也要关闭
# 创建时是先创建连接后创建游标,关闭时是先关闭游标后关闭连接
def __del__(self):
self.cursor.close()
self.conn.close()
seleinum+sql+allure+日志封装
最新推荐文章于 2024-09-10 21:51:16 发布