繁体   English   中英

Pandas read_sql with where 子句使用“in”

[英]Pandas read_sql with where clause using "in"

帮助!

我需要使用“in”子句查询一个表,其中的 SQL 如下所示:

select * from some_table where some_field in (?)

我最初采取了一种天真的方法并尝试了这个:

in_items = [1,2,3,4]
df = pd.read_sql(MY_SQL_STATEMENT, con=con, params=[in_items]

哪个不起作用,它会引发以下错误:

The SQL contains 1 parameter markers, but 4 parameters were supplied

我遇到的问题是弄清楚如何将项目列表作为单个参数传递。

我可以使用字符串连接方法,例如:

MY_SQL = 'select * from tableA where fieldA in ({})'.format(
  ','.join([str(x) from x in list_items]))
df = pd.read_sql(MY_SQL, con=con)

如果可能,我宁愿避免这种方法。 有人知道将值列表作为单个参数传递的方法吗?

我也愿意接受一种可能更聪明的方法来做到这一点。 :)

简单地对占位符进行字符串格式化,然后将您的参数传入pandas.read_sql 请注意,占位符标记取决于 DB-API: pyodbc / sqlite3使用 qmarks ? 大多数其他人使用%s 下面假设前一个标记:

in_items = [1,2,3,4]
MY_SQL = 'select * from tableA where fieldA in ({})'\
           .format(', '.join(['?' for _ in in_items]))
# select * from tableA where fieldA in (?, ?, ?, ?)

df = pd.read_sql(MY_SQL, con=con, params=[in_items])

对我来说,使用 sqllite3,是这样工作的:

list_of_entries_to_retrive = pd.read_excel('.table_with_entries.xlsx')
list_of_entries_to_retrive = (cell_list['entries']).tolist()

conn = sqlite3.connect('DataBase.db')

queryString = 'SELECT * FROM table WHERE attribute IN (\'{}\');'.format('\',\''.join([_ for _ in list_of_entries_to_retrive]))
df = pd.read_sql(queryString, con=conn)

不要这样工作:

df = pd.read_sql(queryString, con=conn,  params=[list_of_entries_to_retrive]))

谢谢

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM