軟件測試 | python數(shù)據(jù)持久化技術(shù)
數(shù)據(jù)持久化技術(shù)
數(shù)據(jù)持久化是指數(shù)據(jù)存儲,目前后端多利用數(shù)據(jù)庫存儲數(shù)據(jù),數(shù)據(jù)庫主要分為兩大類:
傳統(tǒng)數(shù)據(jù)庫連接方式:mysql(PyMySQL)
ORM 模型:SQLAlchemy MyBatis、 Hibernate
ORM 模型是利用語言特性,操作數(shù)據(jù)庫,比如 Python 對象的操作,操作內(nèi)容會映射到數(shù)據(jù)庫里
PyMySQL
安裝:
pip install pymysql
簡單使用
利用pymysql.connect建立數(shù)據(jù)庫連接并執(zhí)行SQL命令(需要提前搭建好數(shù)據(jù)庫):
import pymysql
db = pymysql.connect(
# mysql 地址
host='182.92.129.158',
# 賬號和密碼
user='tmp',
password='ceshiren.com',
# 數(shù)據(jù)庫
db='tmp',
charset='utf8mb4'
)
if __name__ == '__main__':
with db.cursor() as cursor:
# 查看數(shù)據(jù)庫中有多少表
sql = "show tables;"
# 執(zhí)行 sql 語句
cursor.execute(sql)
# 查看所有數(shù)據(jù)
print(cursor.fetchall())
# 查詢 name = aaaaaa 的數(shù)據(jù)
sql = "select * from test_case_table where name=%s"
cursor.execute(sql, ["aaaaaa"])
print(cursor.fetchall())
(('test_case_table',),)
(('aaaaaa', '新的測試用例', 'test_hello.py', 'def test'),)
OPM
對象關(guān)系映射( object-relational mapping) 利用語言特性,操作數(shù)據(jù)庫,比如對 Python 對象的操作, 操作內(nèi)容會映射到數(shù)據(jù)庫里。
SQLALchemy 是 Python 編程語言下的一款 ORM 框架,該框架建立在數(shù)據(jù)庫 API 之上,使用關(guān)系對象 映射進(jìn)行數(shù)據(jù)庫操作。
SQLAchemy 本身無法操作數(shù)據(jù)庫,要依賴 pymysql 三方庫
安裝
pip3 install SQLAlchemy
安裝完成后可創(chuàng)建數(shù)據(jù)庫連接:
engine = create_engine("mysql+pymysql://tmp:ceshiren.com@182.92.129.158/tmp?
charset=utf8",echo=True,)
1.echo:當(dāng)設(shè)置為True時會將ORM語句轉(zhuǎn)化為SQL語句打印,一般debug的時候可用。
2.字段解釋:
3.mysql+pymysql:連接方式,采用pymysql.
4.tmp:ceshiren.com:用戶名:密碼。
5.182.92.129.158/tmp:數(shù)據(jù)庫地址喝數(shù)據(jù)庫名稱。
創(chuàng)建數(shù)據(jù)庫
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import declarative_base
engine = create_engine("mysql+pymysql://tmp:ceshiren.com@182.92.129.158/tmp?
charset=utf8",
echo=True,
)
# 其子類將 Python 類和數(shù)據(jù)庫表關(guān)聯(lián)映射起來
Base = declarative_base()
# 繼承 Base
class Users(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True)
name = Column(String(64), unique=True)
def __init__(self, name):
self.name = name
if __name__ == '__main__':
# 生成數(shù)據(jù)庫表,如果有此庫會忽略
Base.metadata.create_all(engine)
declarative_base() 是 SQLALchemy 內(nèi)部封裝的一個方法,可以讓其子類將 Python 類和數(shù)據(jù)庫表關(guān)聯(lián)映 射起來。
增和查
SQLALchemy 使用 Session 用于創(chuàng)建程序和數(shù)據(jù)庫之間的會話,通過 Session 對象可實現(xiàn)對數(shù)據(jù)的增刪 改查
from sqlalchemy.orm import sessionmaker
# 創(chuàng)建session
Session = sessionmaker(bind=engine)
session = Session()
# 添加新數(shù)據(jù)
add_user = Users("student1")
# 提交
session.add(add_user)
session.commit()
# 查詢
result = session.query(Users).filter_by(name="student1").first()
print(result.id, result.name)
上述代碼新增數(shù)據(jù)后進(jìn)行查詢,結(jié)果如下:
1 student1