python - 接口自动化测试 - MysqlUtil - 数据库操作封装

 

 

# -*- coding:utf-8 -*-

'''
@project: ApiAutoTest
@author: Jimmy
@file: mysql_util.py
@ide: PyCharm Community Edition
@time: 2018-12-22 10:30
@blog: https://www.cnblogs.com/gotesting/

'''

'''
1. 连接数据库
2. 查询
3. 建立游标
4. 执行
'''
import pymysql
import traceback
from Common.read_config import ReadConfig


class MysqlUtil:

    # 读取配置文件中的数据库配置信息,连接数据库
    def __init__(self):
        read_config = ReadConfig()
        host = read_config.get_config_str('mysql','host')
        port = read_config.get_config_int('mysql','port')
        user = read_config.get_config_str('mysql','user')
        password = read_config.get_config_str('mysql','pwd')
        try:
            self.mysql = pymysql.connect(host=host,port=port,user=user,password=password,cursorclass=pymysql.cursors.DictCursor)
        except Exception as e:
            print('mysql connect failed , please check')
            raise e


    # 查询sql数据,并返回
    def fetch_one(self,sql):
        db = self.mysql
        cursor = db.cursor() # 建立游标
        try:
            cursor.execute(sql) # 执行sql语句
            result = cursor.fetchone() # 返回一条数据
        except:
            traceback.print_exc() # 输出异常信息
            db.rollback()
        return result

    def fetch_all(self,sql):
        db = self.mysql
        cursor = db.cursor()
        try:
            cursor.execute(sql)
            result = cursor.fetchall()
        except:
            traceback.print_exc()
        return result

 

posted @ 2018-12-22 16:18  JiaxyGogogo  阅读(1457)  评论(0编辑  收藏  举报