10.PyMySQL模塊

PyMySQL模塊

  1. 安裝PyMySQL模塊

    pip install pymysql
    

  1. PyMySQL查詢數(shù)據(jù)

    import pymysql
    # 連接數(shù)據(jù)庫
    connection = pymysql.connect(host='127.0.0.1', user='root', password='123456', database='DB')
    # 獲取游標對象,cursor=pymysql.cursors.DictCursor 表示返回字典類型的數(shù)據(jù)
    cursor = connection.cursor(cursor=pymysql.cursors.DictCursor)
    # 需要執(zhí)行的sql語句,一般情況下Python只操作數(shù)據(jù)表中的數(shù)據(jù),查詢用戶信息表中的user和password
    sql = 'select * from user_info where user=%s and password=%s;'
    # 執(zhí)行MySQL命令,sql后面?zhèn)魅雞ser和password參數(shù),可以防止sql注入
    cursor.execute(sql,(user,password))
    
    # 獲取執(zhí)行MySQL命令的一個值
    result = cursor.fetchone()
    # 獲取執(zhí)行MySQL命令的多個值
    result = cursor.fetchmany(10)
    # 獲取執(zhí)行MySQL命令的所有值
    result = cursor.fetchall()
    
    # 關(guān)閉游標對象
    cursor.close()
    # 斷開數(shù)據(jù)庫連接
    connection.close()
    

  1. PyMySQL增、刪、改數(shù)據(jù)

    import pymysql
    # 連接數(shù)據(jù)庫
    connection = pymysql.connect(host='127.0.0.1', user='root', password='123456', database='DB')
    # 獲取游標對象
    cursor = connection.cursor(cursor=pymysql.cursors.DictCursor)
    # 需要執(zhí)行的sql語句
    sql = 'insert into tb(username,password) values ("python","123456");'
    
    try:
        # 執(zhí)行MySQL命令
        cursor.execute(sql)
        # 提交到數(shù)據(jù)庫執(zhí)行,查詢不用寫這句,但增、刪、改需要
        connection.commit()
    except Exception as e:
        # 如果出現(xiàn)異常,打印異常
        print(e)
        # 如果出現(xiàn)異常則回滾try中的語句
        connection.rollback()
    
    # 關(guān)閉游標對象
    cursor.close()
    # 斷開數(shù)據(jù)庫連接
    connection.close()
    

?著作權(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ù)。

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