[英]Why does Snowflake variable binding in query throw error with table name but not integer?
我正在關注Snowflake Python Connector文檔進行變量綁定以避免 SQL 注入。 我使用以下憑據成功建立了一個數據庫連接:
import snowflake.connector
CONN = snowflake.connector.connect(
user=snowflake_creds['user'],
password=snowflake_creds['password'],
account=snowflake_creds['account'],
warehouse=snowflake_creds["warehouse"],
database=snowflake_creds['database'],
schema=snowflake_creds['schema'],
)
cur = CONN.cursor(snowflake.connector.DictCursor)
以下塊工作正常,我得到查詢結果,硬編碼表名並使用標准format
綁定:
command = ("SELECT * FROM TEST_INPUT_TABLE WHERE batch_id = %s")
bind_params = (2)
results = cur.execute(command % bind_params).fetchall()
同樣,這個塊工作正常,使用pyformat
綁定:
command = ("SELECT * FROM TEST_INPUT_TABLE WHERE batch_id = %(id)s")
bind_params = {"id": 2}
results = cur.execute(command, bind_params).fetchall()
但是以下兩個塊都導致ProgrammingError
(粘貼在第二個塊下方):
command = ("SELECT * FROM %s WHERE batch_id = %s")
bind_params = ("TEST_INPUT_TABLE", 2)
results = cur.execute(command, bind_params).fetchall()
command = ("SELECT * FROM %(tablename)s WHERE batch_id = %(id)s")
bind_params = {
"tablename": "TEST_INPUT_TABLE",
"id": 2
}
results = cur.execute(command, bind_params).fetchall()
ProgrammingError: 001011 (42601): SQL compilation error:
invalid URL prefix found in: 'TEST_INPUT_TABLE'
字符串和整數的插值方式有什么區別嗎? 我不認為這會有所作為,但這就是我能想到的。 我在這里錯過了一些簡單的東西嗎? 我不想在硬編碼表名和將系統置於 SQL 注入風險之間做出選擇。 感謝您的任何指導。
當綁定變量引用 object 時,您應該使用INDENTIFER()
function 而非字符串文字來包裝綁定變量。 例如:
command = ("SELECT * FROM IDENTIFIER(%(tablename)s) WHERE batch_id = %(id)s")
https://docs.snowflake.com/en/sql-reference/identifier-literal.html
試試看。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.