python操作數(shù)據(jù)庫

在做自動化測試的過程中,有時候需要操作數(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

四、刪除數(shù)據(jù)

五、創(chuàng)建數(shù)據(jù)庫表

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容