• 接口自动化测试:python连接mysql方法封装


    import pymysql
    
    db_conf = {
        "host": "xxxxxxx",
        "port": 3306,
        "user": "root",
        "passwd": "123456",
        "charset": "utf8",  # "utf-8"会报错
    }
    
    
    class DbConnect():
        def __init__(self, db_conf, database="dailyfresh"):
            self.db_conf = db_conf
            # 连接数据库
            self.db = pymysql.Connect(database=database,
                                      cursorclass=pymysql.cursors.DictCursor,
                                      **db_conf,
                                      )
            # 获取操作游标
            self.cursor = self.db.cursor()
    
        def select(self, sql):
            """
            :param sql: sql查询语句
            :return:
            """
            self.cursor.execute(sql)
            results = self.cursor.fetchall()
            return results
    
        def execute(self, sql):
            """
            :param sql:删除、修改、新增语句
            :return:
            """
            try:
                # 执行SQL语句
                self.cursor.execute(sql)
                self.db.commit()
            except:
                # 发生错误时回滚
                self.db.rollback()
    
        def close(self):
            # 关闭数据库连接
            self.db.close()
    
    
    def select_sql(sql):
        db = DbConnect(db_conf)
        results = db.select(sql)
        db.close()
        return results
    
    
    def execute_sql(sql):
        db = DbConnect(db_conf)
        results = db.execute(sql)
        db.close()
    
    
    if __name__ == '__main__':
        db = DbConnect(db_conf)
        sql = "SELECT * FROM df_goods"
        results = db.select(sql)
        db.close()
        print(results)
  • 相关阅读:
    XMU1349 xmu_1349
    字符串排序
    linux磁盘文件与目录管理系统(2)
    poj 3667 Hotel
    poj 3468 A Simple Problem with Integers
    linux文与目录管理
    Linux的磁盘与文件管理系统(1)
    hdu 1698 Just a Hook
    poj3225 Help with Intervals
    poj 2886Who Gets the Most Candies?
  • 原文地址:https://www.cnblogs.com/Xiaojiangzi/p/13784212.html
Copyright © 2020-2023  润新知