我正在尝试将相同的参数传递给SQL代码中两个单独位置的oracle查询。
如果我像这样对table2的条件进行硬编码,我的代码将起作用:
# define parameters
years = ['2018','2019']
placeholder= ':d'
placeholders= ', '.join(placeholder for unused in years)
placeholders
# create cursor
cursor = connection.cursor()
# query
qry = """
select * from table1
INNER
JOIN table2
ON table1_id = table2_id
where table1_year in (%s)
and table2_year in ['2018','2019'] --here's where I say I'm hard coding criteria
""" % placeholders
data = cursor.execute(qry, years)
df = pd.DataFrame(data.fetchall(), columns = [column[0] for column in cursor.description])
# close database connection
connection.close()
如果我尝试像这样使用table2的参数:
qry = """
select * from table1
INNER
JOIN table2
ON table1_id = table2_id
where table1_year in (%s)
and table2_year in (%s) --part of code I'm having issues with
""" % placeholders
我收到以下错误:
TypeError: not enough arguments for format string
我不能简单地重写SQL,因为我经常不得不使用别人的代码,而重写所有代码也不可行。
答案 0 :(得分:1)
如果要填充多个占位符,则必须提供相同数量的参数。
"one meal: %s" % "sandwich" # works
"two meals: %s, %s" % "sandwich" # not working
"two meals: %s, %s" % ("sandwich", "sandwich") # works
注意:在SQL查询的汇编中使用字符串格式(查找“ SQL注入”)是一件坏事/危险的事情。就您而言,这很好,但是通常应使用参数化查询,尤其是在处理来自不受信任来源(如用户输入)的输入时。您不希望用户输入“ 2018; DROP TABLE table1;”。