【问题标题】:executing a raw sql query from sqlalchemy on postgresql在 postgresql 上从 sqlalchemy 执行原始 sql 查询
【发布时间】:2018-09-08 23:07:04
【问题描述】:

我有一个原始的 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>

我使用了来自 here 的引用,但与那里的解决方案不同的是,我得到了一个 ResultProxy 对象。

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

【问题讨论】:

    标签: python postgresql sqlalchemy flask-sqlalchemy


    【解决方案1】:

    正如SQLAlchemy documentation 所解释的那样,.execute() 方法仅返回一个代理,您必须在该代理上进行迭代(或应用任何聚合方法)才能查看查询的实际结果。显然,就您而言,您想要的是.fetchall() method

    如果你尝试这样的事情:

    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

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-16
      • 2015-11-08
      • 1970-01-01
      • 2015-10-20
      • 1970-01-01
      • 2012-12-06
      相关资源
      最近更新 更多