」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何使用SQLalchemy的`connection.execute`使用命名參數來更安全,更可讀的SQL查詢?

如何使用SQLalchemy的`connection.execute`使用命名參數來更安全,更可讀的SQL查詢?

發佈於2025-03-24
瀏覽:518

How Can I Use Named Parameters with SQLAlchemy's `connection.execute` for Safer and More Readable SQL Queries?
使用sqlalchemy connection.execute

SQLAlchemy's text() function to parse the SQL string:

sql = text("SELECT users.fullname || ', ' || addresses.email_address AS title FROM users, addresses WHERE users.id = addresses.user_id AND users.name BETWEEN :x AND :y AND (addresses.email_address LIKE :e1 OR addresses.email_address LIKE :e2)”)將命名參數傳遞到execute()函數:

conn.execute(sql,sql,{“ x”:“ m”:“ m”,“ y”,“ y”,“ y”:z“:” z“,e1”,“ e1”:“%@@@@@@@@@@equ 2”: "%@msn.com"})

Benefits of Named Parameters

Employing named parameters offers several benefits:
  1. Reduced Risk of SQL Injections:
    sql = text("SELECT users.fullname || ', ' || addresses.email_address AS title FROM users, addresses WHERE users.id = addresses.user_id AND users.name BETWEEN :x AND :y AND (addresses.email_address LIKE :e1 OR addresses.email_address LIKE :e2)")
    改進的代碼可讀性:
  2. 名為參數使代碼更易讀,更易於理解,尤其是在處理複雜的查詢時,涉及涉及多個參數的複雜查詢。方法
  3. 也可以定義一個函數來包裝execute函數並接受命名parameters作為字典:

    連接= Engine.connect() 嘗試: 行= Connection.execute(sql,values) ... 最後: Connection.Close() 返回結果

    在此方法中,可以通過以下方式執行查詢:
    conn.execute(sql, {"x": "m", "y": "z", "e1": "%@aol.com", "e2": "%@msn.com"})
    此方法在維護原始代碼的核心功能時啟用了命名參數的利用。
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3