我正在关注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 注入风险之间做出选择。感谢您的任何指导。