[英]executing a raw sql query from sqlalchemy on postgresql
I have a raw sql query which is: 我有一个原始的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;
which in psql
returns: 在
psql
返回:
user_id
---------
7
24
(2 rows)
Now when i run this raw sql query via sqlalchemy I'm getting a sqlalchemy.engine.result.ResultProxy
object in response and not the result as above. 现在,当我通过sqlalchemy运行此原始sql查询时,得到的是
sqlalchemy.engine.result.ResultProxy
对象作为响应,而不是上述结果。 The code i'm using right now is as follows: 我现在使用的代码如下:
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>
I used the reference from here but unlike the solution there I'm getting a ResultProxy object. 我从这里使用了引用,但是与解决方案不同,我得到了一个ResultProxy对象。
What am I doing wrong here? 我在这里做错了什么? My end goal is to get the list of users returned from executing the raw sql-query, stored into a list.
我的最终目标是获取执行原始sql查询返回的用户列表,并将其存储在列表中。
As explained is the SQLAlchemy documentation , the .execute()
method returns only a proxy on which you'll have to iterate (or apply any aggregation method) to view the actual result of the query. 如SQLAlchemy文档所述,
.execute()
方法仅返回一个代理,您必须在该代理上进行迭代(或应用任何聚合方法)以查看查询的实际结果。 Apparently, in your case, what you want is the .fetchall()
method . 显然,对于您而言,您想要的是
.fetchall()
方法 。
If you try something like this: 如果您尝试这样的事情:
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()
the results
variable will be a list
of all the items that the query fetches. results
变量将是查询获取的所有项目的list
。
Hope this helps! 希望这可以帮助!
its resolved now, the issue was because i was converting the query to text
type before passing it to the engine for execution which now i think isn't required when executing a raw sql through the engine. 现在它已解决,问题是因为我在将查询传递给引擎执行之前将查询转换为
text
类型,现在我认为通过引擎执行原始sql时不需要。 So the only change i did in my code was this: 因此,我在代码中所做的唯一更改是:
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.