在做自動化測試的過程中,有時候需要操作數(shù)據(jù)庫,下面就用pymysql連接數(shù)據(jù)庫,并實現(xiàn)簡單的增刪改查詢功能
一、查詢
目標:獲取learn_activity表中name="測試"的id值

image.png
import pymysql
# 連接數(shù)據(jù)庫,指定數(shù)據(jù)庫的ip地址,賬號、密碼、端口號、要操作的數(shù)據(jù)庫
conn = pymysql.connect(host='***.***.80.155', port=3307, user='root', passwd='*****', db='leawod_learn')
# 創(chuàng)建游標
cursor = conn.cursor()
# SQL查詢語句
sql = "select * from learn_activity where name = '測試'"
try:
# 執(zhí)行SQL語句
cursor.execute(sql)
# 獲取所有記錄列表
results = cursor.fetchall()
# print(results)
for i in results:
print(i)
id = i[0]
print("id值是:%s"%id)
except:
# 如果發(fā)生錯誤則回滾
conn.rollback()
# 關(guān)閉數(shù)據(jù)庫連接
conn.close()
運行結(jié)果:
(237291614169858048, '測試', '/20190517/b93de77c-acb2-4286-8cdd-ab65e3a8874d.jpg', '<p><img src="/20190517/3ea80fc6-a68a-42c4-afb7-9041edaaa0d1.jpg""></p><p>測試</p>', 1, 1, '', '', 0, 105, 1, 16, datetime.datetime(2019, 5, 17, 19, 12, 9), datetime.datetime(2019, 6, 27, 16, 10, 6), 0)
id值是:237291614169858048
二、插入數(shù)據(jù)
目標:向student表中添加一條數(shù)據(jù),id=1,first_name=李, last_name=四

image.png
import pymysql
# 連接數(shù)據(jù)庫,指定數(shù)據(jù)庫的ip地址,賬號、密碼、端口號、要操作的數(shù)據(jù)庫
conn = pymysql.connect(host='192.168.**.***', port=3306, user='root', passwd='123456', db='employees')
# 創(chuàng)建游標
cursor = conn.cursor()
# SQL插入語句
sql = "insert into student values (1, '李', '四')"
try:
# 執(zhí)行SQL語句
cursor.execute(sql)
#關(guān)閉游標,提交,關(guān)閉數(shù)據(jù)庫連接
# 如果沒有這些關(guān)閉操作,執(zhí)行后在數(shù)據(jù)庫中查看不到數(shù)據(jù)
cursor.close()
# 提交到數(shù)據(jù)庫執(zhí)行
conn.commit()
except:
# 如果發(fā)生錯誤則回滾
conn.rollback()
# 關(guān)閉數(shù)據(jù)庫連接
conn.close()
執(zhí)行結(jié)果:

insert.png
三、修改數(shù)據(jù)
目標:把 id=1 的 first_name 由 “李” 改為 “王”

image.png