如何在sql语句中插入多个ID?

时间:2017-10-20 10:07:01

标签: python pandas

python和pandas的新手,我面临以下问题:

我想将多个字符串传递给sql查询并努力插入分隔符',' :

Example data

import pandas as pd

data = [['Alex',10],['Bob',12],['Clarke',13]]
df = pd.DataFrame(data,columns=['Name','Age'])
print (df)

# Remove header (Not sure whether that is necessary)
df.columns = df.iloc[0]


pd.read_sql(

    """
SELECT
*

FROM emptable
WHERE empID IN ('{}',)

    """.format(df.ix[:, 0]), # Which corresponds to 'Alex','Bob','Clarke'

    con = connection)

我尝试了不同的组合,但是没有一个组合。

1 个答案:

答案 0 :(得分:2)

演示:

sql_ = """
SELECT *
FROM emptable
WHERE empID IN ({})
"""

sql = sql_.format(','.join([x for x in ['?'] * len(df)]))
print(sql)

new = pd.read_sql(query, conn, params=tuple(df['Name']))

输出:

In [166]: print(sql)

SELECT *
FROM emptable
WHERE empID IN (?,?,?)

注意:如果您的DF很大,这种方法将无效,因为生成的SQL字符串太大。

在这种情况下,您可以将名称保存/转储到帮助程序临时表中,并在SQL中使用它:

df[['Name']].to_sql('tmp', conn, if_exists='replace')

sql = """
SELECT *
FROM emptable
WHERE empID IN (select Name from tmp)
"""
new = pd.read_sql(sql, conn)