簡體   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