以下逻辑用于转换,以便将字符串列表转换为每个字符串都用引号和逗号分隔
>>> record_hash
['AAA', 'BBB', 'CCC']
>>> t="'"+"','".join(record_hash)+"'"
>>> t
"'AAA','BBB','CCC'"
>>>
此逻辑传递给下面的逻辑以形成SQL语句以形成where column in
条件
def selectAllPackageType(record_hash, severity):
t="'"+"','".join(record_hash[])+"'"
joined_string = ', '.join(['"{}"'.format(value) for value in record_hash])
sql = 'select package_type from slack_jira where severity = ? and record_hash in (?)'
print(sql)
conn = getSQLConnection();
package_type = []
conn.set_trace_callback(print)
if conn is not None:
cursor = conn.cursor()
cursor.execute(sql,(severity,t))
records = cursor.fetchall()
for row in records:
package_type.append(row['package_type'])
cursor.close()
conn.close()
else:
print("Error! cannot perform selectByPackageType.")
return package_type
conn.set_trace_callback(print)
打印此值,因为它包含一个记录,导致获取记录失败
select package_type from slack_jira where severity = 'MEDIUM' and record_hash in ('''AAAAA'',''CCCC''');
所需要的是形成正确的SQL语句,以正确的转义来创建where column in (?)
select package_type from slack_jira where severity = 'MEDIUM' and record_hash in ('AAAAA','CCCC');
答案 0 :(得分:1)
我知道了,这很有效
result_set = conn.execute("SELECT * FROM slack_jira WHERE severity='MEDIUM' and id IN (%s)" % ','.join('?'*len(record_hash)), record_hash)
>>> import sqlite3
>>> conn = sqlite3.connect('/tmp/test.db')
>>> conn.set_trace_callback(print)
>>> record_hash=['A','B']
>>> result_set = conn.execute("SELECT * FROM slack_jira WHERE severity='MEDIUM' and id IN (%s)" % ','.join('?'*len(record_hash)), record_hash)
SELECT * FROM slack_jira WHERE severity='MEDIUM' and id IN ('A','B')