1. <optgroup id="o3fot"></optgroup>
    <big id="o3fot"></big>
  2. <label id="o3fot"></label>
  3. 教育行業A股IPO第一股(股票代碼 003032)

    全國咨詢/投訴熱線:400-618-4000

    有哪些策略可以防止SQL注入?

    更新時間:2023年01月14日12時01分 來源:傳智教育 瀏覽次數:

    用戶提交帶有惡意的數據與SQL語句進行字符串方式的拼接,從而影響了SQL語句的語義,最終產生數據泄露的現象。

    防止SQL注入可以將SQL語句參數化

    •SQL語言中的參數使用%s來占位,此處不是python中的字符串格式化操作

    •將SQL語句中%s占位所需要的參數存在一個列表中,把參數列表傳遞給execute方法中第二個參數

    防止SQL注入的示例代碼:

    from pymysql import connectdef main():
    
        find_name = input("請輸入物品名稱:")    # 創建Connection連接
        conn = connect(host='localhost',port=3306,user='root',password='mysql',database='jing_dong',charset='utf8')    # 獲得Cursor對象
        cs1 = conn.cursor()    # 非安全的方式
        # 輸入 ' or 1 = 1 or '   (單引號也要輸入)
        # sql = "select * from goods where name='%s'" % find_name
        # print("""sql===>%s<====""" % sql)
        # # 執行select語句,并返回受影響的行數:查詢所有數據
        # count = cs1.execute(sql)
    
        # 安全的方式
        # 構造參數列表
        params = [find_name]    # 執行select語句,并返回受影響的行數:查詢所有數據
        count = cs1.execute("select * from goods where name=%s", params)    # 注意:
        # 如果要是有多個參數,需要進行參數化
        # 那么params = [數值1, 數值2....],此時sql語句中有多個%s即可
        # %s 不需要帶引號
    
        # 打印受影響的行數
        print(count)    # 獲取查詢的結果
        # result = cs1.fetchone()
        result = cs1.fetchall()    # 打印查詢的結果
        print(result)    # 關閉Cursor對象
        cs1.close()    # 關閉Connection對象
        conn.close()if __name__ == '__main__':
        main()

    注意:execute方法中的 %s 占位不需要帶引號。

    0 分享到: