python ibm\u db列表

a0x5cqrl  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(352)

我使用python读入csv文件中的名称,然后将这些名称合并到sql查询中。使用ibmsql,我试图将list变量放在sql中 WHERE 条款: WHERE IN (List) 我该如何引用列表 sampleWHERE 条款?: WHERE a.name IN (sample) ```

pip install ibm-db

import ibm_db_dbi as db

conn = db.connect("DATABASE=xxx;HOSTNAME=xxx;PORT=xxx;PROTOCOL=TCPIP;UID=xxx;PWD=xxx;", "", "")
with open('file.csv', newline='') as f:
reader = csv.reader(f)
next(reader, None) #skip header
data = list(reader) #list
sample = data[:20]

sql

cursor = conn.cursor()
sql = '''
SELECT name
FROM (

SELECT DISTINCT a.name, b.number
FROM table1 as a
JOIN table2 as b ON a.sk = b.sk
WHERE a.name IN _____________ <<<
order by b.number
)
group by name
'''
#{}.format(sample)
cursor.execute(sql)

for r in cursor.fetchall():
print(r)

yfwxisqw

yfwxisqw1#

考虑插入一个逗号分隔的qmark列表, ? (等于列表中的项目数)。然后,将列表作为参数传递给 execute 电话:

sql = '''SELECT name
         FROM (
             SELECT DISTINCT a.name, b.number
             FROM table1 as a
             JOIN table2 as b ON a.sk = b.sk
             WHERE a.name IN ({})
             ORDER BY b.number
         ) sub
         GROUP BY name
      '''

qmarks = ", ".join(['?' for i in sample])

cursor.execute(sql.format(qmarks), sample)

for r in cursor.fetchall():
    print(r)

相关问题