从0开始一步步搭建selenium+python+pymysql+HTMLTestRunner 自动化测试框架(五)
第五步:准备数据连接的公共方法,获取数据库连接:传入参数是配置文件中的数据库连接信息,返回pymysql的connect对象
# encoding=utf-8
import configparser
import os
import pymysql
from automation_framework.logger.logger import Logger
logger = Logger(logger="DataBaseInit").getlog()
def connect(database):
config = configparser.ConfigParser()
file_path = os.path.dirname(os.path.abspath('.')) + '/config/config.ini'
config.read(file_path)
host = config.get(database, "host") # 获取数据库链接的host
logger.info("You had select %s host." % host) # 日志打印你选择的数据库
port = config.get(database, "port") # 获取数据库的端口号
dbname = config.get(database, "dbname") # 获取数据库名
username = config.get(database, "username") # 获取数据库用户名
password = config.get(database, "password") # 获取数据库密码
#
try:
# 连接mysql数据库中具体某个库
conn = pymysql.connect(
host=host,
port=int(port),
user=username,
database=dbname,
password=password
)
# 获取数据库游标
return conn
except pymysql.Error as e:
raise e