1. 程式人生 > 其它 >debugtalk.py輔助函式 - 連線資料庫

debugtalk.py輔助函式 - 連線資料庫

連線資料庫

  介面操作完成後,校驗資料庫   1.首先安裝mysql驅動包pymysql     pip install pymysql

  連線資料庫進行增刪改查

    connect_mysql.py
import pymysql

# 配置資料庫相關資訊
dbinfo = {
    "host": "127.0.0.1",
    "user": "root",
    "password": "123456",
    "port": 8080
}

class DbConnect(object):
    def __init__(self, db_cof, database=""
): # 開啟資料庫連線 self.db = pymysql.connect(database=database, cursorclass=pymysql.cursors.DictCursor, **db_cof) # 使用cursor()方法獲取操作遊標 self.cursor = self.db.cursor() print("連線成功") def select(self, sql): # sql查詢語句 # sql = 'select * from table where name="張三"
' self.cursor.execute(sql) results = self.cursor.fetchall() print("查詢成功") return results def execute(self, sql): # sql刪除、提交、修改語句 print("刪除成功") try: self.cursor.execute(sql) # 執行sql語句 self.db.commit() # 提交修改 except: # 發生錯誤時回滾 self.db.rollback() def close(self): # 關閉連線 self.db.close()
if __name__ == "__main__": db = DbConnect(dbinfo, database='info') sql = 'select * from info where id=1;' res = db.select(sql) print(res) sql1 = 'delete from info where id =2;' res1 = db.execute(sql) print(res1)

  測試結果校驗資料庫狀態

    debugtalk.py
from utils.connect_mysql import DbConnect, dbinfo

def get_db_info(user_id,key='id'):
    db = DbConnect(dbinfo, database='info')
    sql = 'select * from info where id=%s;' % user_id
    res = db.select(sql)
    print(res)
    if len(res) == 0:
        result = ''
    else:
        result = res[0][key]
    return result
if __name__ == "__main__":
    r = get_db_info(user_id=1)
    print(r)

    update_info.py

config:
    name: 修改使用者資訊用例
    base_url: http://127.0.0.1:8080
    variables:
        user_id: 1
        username: "zhangsan"
        usertel: 13333333333
        usersex: "m"
        birthaddress: "羊村"
        birthday: 2000-01-01
        schoolname: "藍翔技校"

teststeps:
-
    name: 修改使用者資訊
    request:
        url: /api/test/info/$user_id
        method: PUT
        json:
            username: $username
            usertel: $usertel
            usersex: $usersex
            birthaddress: $birthaddress
            birthday: $birthday
            schoolname: $schoolname
    validate:
        - eq: [status_code, 200]
        - eq: [body.code, 1000]
        - eq: [body.msg, success!]
        - eq: [body.data.goodsstatus, '${get_db_info($user_id)}']