【Python+postman介面自動化測試】(12)Python 操作資料庫
阿新 • • 發佈:2021-11-10
Python 操作資料庫
在功能、介面測試中常常需要通過資料庫的操作,來準備資料、檢測環境及核對功能、介面的資料庫操作是否正確。 在自動化測試中,就需要我們用程式碼連線資料庫自動完成資料準備、環境檢查及資料庫斷言的功能。 使用Python操作MySQL資料庫這裡我們需要用到三方庫Pymysql安裝方法:pip install pymysql
1、資料庫操作
1. 建立資料庫連線 conn = pymysql.connect() 2. 從連線建立操作遊標 cur = conn.cursor() 3. 使用遊標執行sql(讀/寫) cur.execute(sql) 4. 獲取結果(讀)/ 提交更改(寫) cur.fetchall() / conn.commit() 5. 關閉遊標及連線 cur.close();conn.close()importpymysql # 建立資料庫連線 conn = pymysql.connect( host='127.0.0.1', port=3306, user='root', password='111111', # passwd也可以 db='school', charset='utf8') # 如果查詢有中文需要指定資料庫編碼 # 從連線建立遊標,有了遊標才能操作資料庫 cur = conn.cursor() # 更改資料庫 cur.execute("INSERT INTO student VALUES ( 777, 'hello.殷', '男', 1990, '歷史', '湖南寧鄉' )") # 查詢資料庫 cur.execute("select * from student where name='hello.殷'") # 獲取查詢結果 result = cur.fetchall() print(result) # 提交更改 conn.commit()
執行結果:
C:\Users\yzp\AppData\Local\Programs\Python\Python37\python.exe D:/00test/RFTEST/mysql.py ((777, 'hello.殷', '男', 1990, '歷史', '湖南寧鄉'),) Process finished with exit code 0什麼是遊標? 遊標類似檔案控制代碼,可以逐條的訪問資料庫執行結果集。pymysql中只能通過遊標來執行sql和獲取結果
2、查詢操作
使用cur.execute(), 執行資料庫查詢後無返回的是影響的行數,而非查詢結果。我們要使用cur.fetchone()/cur.fetchmany()/cur.fetchall()來獲取查詢結果。
- cur.fetchone(): 獲取一條資料(同時獲取的資料會從結果集刪除),返回元祖('張三','123456')
- cur.fetchmany(3): 獲取多條資料,返回巢狀元祖(('張三','123456'),('李四','123456'),("王五","123456"))
- cur.fetchall(): 獲取所有資料,返回巢狀元祖,(('張三','123456'),)(只有一條資料時)
cur.execute(select * from user where name='張三') print(cur.fetchone()) # 結果: ('張三','123456') print(cur.fetchone()) # 結果:None print(cur.fetchall()) # 結果:()
所以我們需要重複使用查詢結果時,需要將查詢結果賦給某個變數
cur.execute(select * from user where name='張三') result = cur.fetchall() print(result) # 結果: ('張三','123456') print(result) # 結果: ('張三','123456')
3、修改操作
執行修改資料庫的操作後不立即生效,使用連線conn.commit()提交後才生效,支援事物及回滾try: cur.execute("insert into user (name,password) values ('張三', '123456')") cur.execute("insert into user (name, passwd) values ('李四'), '123456'") # 此處sql出錯 conn.commit() # 使用連線提交所有更改 except Exception as e: conn.rollback() # 回滾所有更改(注意用的是conn) print(str(e))
4、封裝資料庫操作
由於經常要使用到資料庫操作,建議將所有資料庫操作封裝成公用的資料庫模組4.1新建db.py, 程式碼如下:
import pymysql class DB: def __init__(self): self.conn = pymysql.connect( host='127.0.0.1', port=3306, user='root', password='111111', db='school' ) self.cur = self.conn.cursor() def __del__(self): # 解構函式,例項刪除時觸發 self.cur.close() self.conn.close() def query(self, sql): # 查詢函式 self.cur.execute(sql) return self.cur.fetchall() def exc(self, sql): # 執行函式 try: self.cur.execute(sql) self.conn.commit() except Exception as e: self.conn.rollback() print(str(e)) def check(self, name): result = self.query("select * from student where name='{}'".format(name)) return True if result else False def del_user(self, name): self.exc("delete from student where name='{}'".format(name))
使用方法:
from db import * if check_user("張三"): del_user("張三")4.2 **補充:**另一種封裝方法
由於上面這種封裝方法,每一次查詢都會建立一次資料庫連線,效率較低,也可以採用下面面向物件的封裝方法,新建db2.pyimport pymysql class DB: def __init__(self): self.conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='111111', # passwd 不是 password db='scholl') self.cur = self.conn.cursor() def __del__(self): # 解構函式,例項刪除時觸發 self.cur.close() self.conn.close() def query(self, sql): self.cur.execute(sql) return self.cur.fetchall() def exec(self, sql): try: self.cur.execute(sql) self.conn.commit() except Exception as e: self.conn.rollback() print(str(e)) def check_user(self, name): result = self.query("select * from user where name='{}'".format(name)) return True if result else False def del_user(self, name): self.exec("del from user where name='{}'".format(name))
使用方法:
from db2 import DB: db = DB() # 例項化一個數據庫操作物件 if db.check_user("張三"): db.del_user("張三")
5、後言
- 資料庫連線資訊建議寫到配置檔案中,從配置檔案中讀取
- sql語句建議先在手工測試一下沒有語法問題再進行封裝
- 通過封裝各種sql可以完成各種業務操作
- 更改資料庫有風險,操作需謹慎!!!
本部落格所有文章僅用於學習、研究和交流目的,歡迎非商業性質轉載。
本文來自部落格園,作者:hello_殷,轉載請註明原文連結:https://www.cnblogs.com/yinzuopu/p/15532830.html
本文版權歸作者和部落格園共有,歡迎轉載,但必須給出原文連結,並保留此段宣告,否則保留追究法律責任的權利。