繁体   English   中英

在PostgreSQL上从sqlalchemy执行原始sql查询

[英]executing a raw sql query from sqlalchemy on postgresql

我有一个原始的SQL查询是:

select distinct(user_id) from details_table where event_id in (29,10) and user_id in (7,11,24,45) and epoch_timestamp >= 1433116800 and epoch_timestamp <= 1506816000;

psql返回:

 user_id 
---------
       7
      24
(2 rows)

现在,当我通过sqlalchemy运行此原始sql查询时,得到的是sqlalchemy.engine.result.ResultProxy对象作为响应,而不是上述结果。 我现在使用的代码如下:

from flask import current_app
sql_query = text(select distinct(user_id) from details_table where event_id in (29,10) and user_id in (7,24) and epoch_timestamp >= 1433116800 and epoch_timestamp <= 1506816000;)

filtering_users = db.get_engine(current_app, bind='<my_binding>')\
                    .execute(sql_query)
print(type(filtering_users))
# <class 'sqlalchemy.engine.result.ResultProxy'>
print(filtering_users)
# <sqlalchemy.engine.result.ResultProxy object at 0x7fde74469550>

我从这里使用了引用,但是与解决方案不同,我得到了一个ResultProxy对象。

我在这里做错了什么? 我的最终目标是获取执行原始sql查询返回的用户列表,并将其存储在列表中。

SQLAlchemy文档所述, .execute()方法仅返回一个代理,您必须在该代理上进行迭代(或应用任何聚合方法)以查看查询的实际结果。 显然,对于您而言,您想要的是.fetchall() 方法

如果您尝试这样的事情:

from sqlalchemy import create_engine

engine = create_engine('/path/to/your/db...')
connection = engine.connect()

my_query = 'SELECT * FROM my_table'
results = connection.execute(my_query).fetchall()

results变量将是查询获取的所有项目的list

希望这可以帮助!

现在它已解决,问题是因为我在将查询传递给引擎执行之前将查询转换为text类型,现在我认为通过引擎执行原始sql时不需要。 因此,我在代码中所做的唯一更改是:

sql_query="select distinct(user_id) from details_table where event_id in (29,10) and user_id in (7,11,24,45) and epoch_timestamp >= 1433116800 and epoch_timestamp <= 1506816000"

暂无
暂无

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

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