如何为" IN子句"传递变量参数;

时间:2017-04-12 13:49:12

标签: python python-2.7 cassandra datastax

我正在准备一个session.execute语句,如下所示。 我有几个条件和一个IN条款。我收到以下错误。 我知道我犯了一个错误但却无法使它发挥作用 filter_site_value = ['filter 1', 'filter 2']

session = get_session()
query = 'SELECT * FROM table where cv = %s AND dt > %s and dt < %s AND st IN  (%s)' % ','.join('%s' for i in filter_site_value)
data = (filter_customer_value,filter_date_start_value, filter_date_end_value, filter_site_value)
rows = session.execute(query, data)

&#34; errorType&#34;:&#34; TypeError&#34;,   &#34; errorMessage&#34;:&#34;没有足够的格式字符串参数&#34;

请帮忙。

1 个答案:

答案 0 :(得分:3)

您的字符串有3个位置需要将值格式化(%s),您只提供一个值:','.join('%s' for i in filter_site_value)

所以如果你有:

x = string_to_format % values

和string_to_format包含X量%s(或%d %r ...),那么您需要values中的X值

请参阅: https://docs.python.org/2/library/string.htmlhttps://pyformat.info/

您可能想要做的是:

query = 'SELECT * FROM table where cv = %s AND dt > %s and dt < %s AND st IN  ('+ ','.join(filter_site_value)+')'
data = (filter_customer_value,filter_date_start_value, filter_date_end_value)

query = 'SELECT * FROM table where cv = %s AND dt > %s and dt < %s AND st IN  ('+ ','.join(%s for i in filter_site_value)+')'
data = (filter_customer_value,filter_date_start_value, filter_date_end_value)+tuple(filter_site_value)