如何在python中运行sqlalchemy中的.sql文件

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

我创建了一个 postgres 函数并保存在一个名为

get_data.sql

的文件中
    create or replace function getalldata(entryDate TIMESTAMP, exitDate TIMESTAMP) RETURNS SETOF employee AS $$
    BEGIN
            begin     -- try
                    select employee.name, dept.name
                    from employee 
                    join dept on employee.dept_id=dept.id
                    where  employee.name='Kumar' and 
                    employee.timestamp>=entryDate and employee.timestamp<=exitDate;
            exception when others then 

                raise notice 'The transaction is in an uncommittable state. '
                             'Transaction was rolled back';

                raise notice '% %', SQLERRM, SQLSTATE;
            end ; -- try..catch
    END;
    $$ LANGUAGE plpgsql;

我在 sqlalchemy 中运行这个 sql 文件

    try:
        from sqlalchemy import create_engine, text
        connection = engine.connect()
        with open('get_data.sql', 'r') as file:
            procedure_sql = file.read()

        procedure_sql = text(procedure_sql)

        results = connection.execute(
                procedure_sql,
                {'entryDate':start_datetime, 'exitDate':end_datetime}
            )
        results = list(results.fetchall())
    except Exception as e:
        print('error', e)

但是我收到了这个错误

错误 该结果对象不返回行。已经自动关闭了。

如何解决这个问题,以及导致此错误的原因

python postgresql
1个回答
0
投票

如果您在结果集关闭后尝试获取行,则可能会发生这种情况。

要解决此问题,您应该在执行查询后、关闭结果集之前立即获取行。

试试这个:

results = connection.execute("Your SQL Query").fetchall()
© www.soinside.com 2019 - 2024. All rights reserved.