import os, configparser
class ConfigReader():
def __init__(self, file_name):
self.config = configparser.ConfigParser()
config_path = os.path.split(os.path.realpath(__file__)[0] + os.sep + file_name) # todo:定位文件位置
self.config.read(config_path, "utf-8") # todo:读取文件编码格式为utf-8
def get_option(self, _option):
sections = self.config.sections()
for i in sections:
if self.config.has_option(i, _option):
return self.config.get(i, _option)
class DB():
def __init__(self, DBname):
cf = ConfigReader("databases_config_user.cfg") # todo:读取指定配置文件,如果有多个配置文件还得改
self.host = cf.get_option(DBname + "_host") # todo:获取具体的host地址
self.port = cf.get_option(DBname + "_port") # todo:获取具体的port端口号
self.user = cf.get_option(DBname + "_user") # todo:获取具体的user账号
self.password = cf.get_option(DBname + "_password") # todo:获取具体的数据库密码
self.DBname = DBname
def connect(self): # todo:上面的所有代码都在为这个方法做铺垫,也就是python连接数据库
import pymysql
self.db = pymysql.connect(host=self.host, user=self.user, password=self.password, database=self.DBname)
self.cursor = self.db.cursor() # todo:创建游标
def close(self):
self.cursor.close()
self.db.close() # todo:连接数据库时游标打开,打开就得关闭,别问为啥,出错了就送银手铐了
def get_one(self, sql):
result = 0
try:
self.connect()
self.cursor.execute(sql)
result = self.cursor.fetchone() # todo:利用游标只要一个结果
self.close()
except Exception as e: # todo:获取异常信息别名e
print('select error', e)
return result # todo:sql语句有返回值就出来 没有就返回异常信息
def get_all(self, sql):
result = 0
try:
self.connect()
self.cursor.execute(sql)
result = self.cursor.fetchall()
self.close()
except Exception as e:
print('select error', e)
return result # todo:跟get_one()没有区别就是一个fechone,一个fechall
def _edit(self, sql):
result = 1
try:
self.connect()
self.cursor.execute(sql)
self.db.commit()
self.close()
except Exception as e:
print('erroe', e)
result = 0
self.db.rollback()
return result # todo:如果sql语句正确那就提交返回result=0,语句执行存在异常就回滚一下保证库内数据正确返回result=1
"""_edit(self,sql) 其实就是做个判断,看看sql语句对不对,对就填进去,不对也不会影响库 下面的增删改都是基于这个方法"""
def _insert(self, sql):
return self._edit(sql)
def _update(self, sql):
return self._edit(sql)
def _delect(self, sql):
return self._edit(sql)
print(DB("biexianmafan").get_one("select * from biexianmafan;"))
初识httprunner之读取mysql配置文件以及连接mysql
最新推荐文章于 2023-11-20 17:23:47 发布