如何在Python中调用光标?

问题描述 投票:0回答:1

如何在Python中调用光标

CREATE OR REPLACE PROCEDURE WaterBillInMonth(
       in p_Month INT,
       INOUT refcur refcursor DEFAULT 'rs_resultone'::refcursor)
LANGUAGE 'plpgsql'
AS $BODY$
BEGIN
    OPEN refcur for
    SELECT u.username, w.prev_volume, w.cur_volume, 
        w.total_volume, w.price, w.total_volume_price, w.due_date, w.payment_date, w.created_at
    FROM water_bills w JOIN users u ON w.user_id = u.id
    WHERE p_Month = EXTRACT (MONTH FROM w.created_at);
END;
$BODY$;
-- call procedure
CALL WaterBillInMonth(4, 'rs_resultone');
FETCH ALL FROM rs_resultone;
I want to call cursor (query)

我想从 python 调用它来检索光标的结果。

    stmt = text("CALL WaterBillInMonth(:p_month, 'rs_resultone')")
    result = db.execute(stmt, {'p_month': p_month})
    # bills = result.fetchall()
    bills = result.fetchall()
    print(bills)
    # bills = db.execute(text("FETCH ALL FROM rs_resultone"))
python postgresql sqlalchemy
1个回答
0
投票

要在Python中检索游标结果,可以按照以下步骤操作:

  1. 使用 SQLAlchemy 的 text() 构造执行存储过程。
  2. 从光标处获取结果。

具体操作方法如下:


    from sqlalchemy import create_engine, text
    
    # Assuming you have already created a SQLAlchemy engine
    engine = create_engine('your_database_connection_string')
    
    # Define the month for which you want to retrieve water bills
    p_month = 4
    
    # Execute the stored procedure
    stmt = text("CALL WaterBillInMonth(:p_month, 'rs_resultone')")
    result = engine.execute(stmt, {'p_month': p_month})
    
    # Fetch the results from the cursor
    bills = result.fetchall()
    
    # Print the retrieved bills
    for bill in bills:
        print(bill)
    
    # Close the result set and connection
    result.close()
    engine.dispose()

© www.soinside.com 2019 - 2024. All rights reserved.