如何通过SQLAlchemy查询从Python中过滤名称列表

时间:2016-12-09 17:42:25

标签: python sqlalchemy

我的原始查询就像

select table1.id, table1.value
from some_database.something table1
join some_set table2 on table2.code=table1.code
where table1.date_ >= :_startdate and table1.date_ <= :_enddate

保存在Python中的字符串中。如果我做

x = session.execute(script_str, {'_startdate': start_date, '_enddate': end_date})

然后

x.fetchall()

会给我我想要的桌子。

现在情况是,我在Oracle数据库中不再使用table2,而是在我的python环境中作为DataFrame可用。我想知道在这种情况下从数据库中获取同一个表的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

您可以改为使用IN子句。

首先从join

中删除script_str
script_str = """
select  table1.id, table1.value
from    something table1
where   table1.date_ >= :_startdate and table1.date_ <= :_enddate
"""

然后,从dataframe获取代码:

codes = myDataFrame.code_column.values

现在,我们需要动态地将script_str和参数扩展到查询:

param_names = ['_code{}'.format(i) for i in range(len(codes))]
script_str += "AND table1.code IN ({})".format(
    ", ".join([":{}".format(p) for p in param_names])
)

使用所有参数创建dict:

params = {
    '_startdate': start_date,
    '_enddate': end_date,
}
params.update(zip(param_names, codes))

执行查询:

x = session.execute(script_str, params)
相关问题