我试图在我的python脚本中传递一个sql(如果我在客户端上运行它可以完美地运行),但我收到错误“没有足够的格式字符串参数”
以下,代码:
sql = """
SELECT
rr.iserver,
foo.*, rr.queue_capacity,
rr.queue_refill_level,
rr.is_concurrent,
rr.max_execution_threads,
rr.retrieval_status,
rr.processing_status
FROM
(
SELECT DISTINCT
ip.package,
it. TRIGGER
FROM
wip.info_package ip,
wip.info_trigger it
WHERE
ip.service = it.service and
ip.iserver = '%(iserver)s' and
it.iserver = %(iserver)s'
AND package = '%(package)s'
UNION
SELECT
'%(package)s' AS package,
TRIGGER
FROM
info_trigger
WHERE
TRIGGER LIKE '%(package)s%'
) AS foo,
info_trigger rr
WHERE
rr. TRIGGER = foo. TRIGGER
""" % {'iserver' : var_iserver,'package' : var_package}
dcon = Database_connection()
getResults = dcon.db_call(sql, dbHost, dbName, dbUser, dbPass)
# more and more code to work the result....
我的主要问题是如何正确传递'%(iserver)s' , '%(package)s'
。因为通常,当我在数据库中选择或插入时,我只使用两个变量,但我不知道如何使用两个以上的变量。
感谢。
答案 0 :(得分:7)
不要使用%
构建这样的SQL:
"SELECT %(foo)s FROM bar WHERE %(baz)s" %
{"foo": "FOO", "baz": "1=1;-- DROP TABLE bar;"}
这为令人讨厌的SQL注入攻击打开了大门。
使用适当形式的Python Database API Specification v2.0适配器。对于Psychopg,这个表格被描述为here。
cur.execute("SELECT %(foo)s FROM bar WHERE %(baz)s",
{"foo": "FOO", "baz": "1=1;-- DROP TABLE bar;"})
答案 1 :(得分:6)
WHERE
TRIGGER LIKE '%(package)s%'
你有一个额外的'%'
如果你想要实际的字符'%',你需要用双'''转义。
所以它应该是
WHERE
TRIGGER LIKE '%(package)s%%'
如果您想显示'%'
和
WHERE
TRIGGER LIKE '%(package)s'
如果你不