Python知識(shí)分享網(wǎng) - 專(zhuān)業(yè)的Python學(xué)習(xí)網(wǎng)站 學(xué)Python,上Python222
pymysql執(zhí)行insert插入操作
匿名網(wǎng)友發(fā)布于:2023-09-19 10:44:46
(侵權(quán)舉報(bào))

1小時(shí)學(xué)會(huì) Python操作Mysql數(shù)據(jù)庫(kù)之pymysql模塊技術(shù)https://www.bilibili.com/video/BV1Dz4y1j7Jr

 

 

執(zhí)行修改操作,需要通過(guò)Connection對(duì)象調(diào)用commit()方法確認(rèn)提交,或者 構(gòu)造方法里面,autocommit設(shè)置True,自動(dòng)提交

 

from pymysql import Connection

con = None

try:
    # 創(chuàng)建數(shù)據(jù)庫(kù)連接
    con = Connection(
        host="localhost",  # 主機(jī)名
        port=3306,  # 端口
        user="root",  # 賬戶(hù)
        password="123456",  # 密碼
        database="db_python",  # 指定操作的數(shù)據(jù)庫(kù)
        autocommit=True  # 設(shè)置自動(dòng)提交
    )
    # 獲取游標(biāo)對(duì)象
    cursor = con.cursor()
    # 使用游標(biāo)對(duì)象,執(zhí)行sql語(yǔ)句
    cursor.execute("insert into t_student values(null,'趙六2',25)")
    # 獲取主鍵
    print("主鍵id=", con.insert_id())
    # 確認(rèn)提交
    # con.commit()
except Exception as e:
    print("異常:", e)
finally:
    if con:
        # 關(guān)閉連接
        con.close()

 

 

 

轉(zhuǎn)載自: