【问题标题】:How to call an Oracle function of refcursor return type using sqlalchemy and python如何使用 sqlalchemy 和 python 调用 refcursor 返回类型的 Oracle 函数
【发布时间】:2017-11-11 07:09:49
【问题描述】:

功能如下:

CREATE or replace function get_data(data_key integer) return sys_refcursor 
is
result1 sys_refcursor;
BEGIN

open result1 for 'Select DISTINCT COL1
        FROM REF_TABLE
        where DATA_KEY='||data_key;

return result1;
END;

上述函数的调用

variable rc refcursor;
exec :rc :=get_data(30038);
print rc;

这在 sql developer 中运行良好。 如何使用 python 和 sqlalchemy 调用相同的?

【问题讨论】:

    标签: python oracle plsql sqlalchemy plsqldeveloper


    【解决方案1】:

    我使用了 cx_Oracle 而不是 SQLAlchemy,它起作用了。结果输出与我对 sqlalchemy 的期望相同。我将函数转换为过程。

    程序

    CREATE or replace procedure get_data(data_key in integer, result out 
    sys_refcursor) as
    BEGIN
    
    open result for 'Select DISTINCT COL1
            FROM ref_table
            where DATA_KEY='||data_key;
    
    END;
    

    使用python和cx_Oracle调用上述过程的代码

    import cx_Oracle
    import pandas as pd
    
    conn = cx_Oracle.connect('system/<password>@127.0.0.1/XE')
    cur = conn.cursor()
    
    myvar = cur.var(cx_Oracle.CURSOR)
    cur.callproc('get_data', (30038, myvar))
    data = myvar.getvalue().fetchall()
    if len(data) == 0:
        data = {}
    df = pd.DataFrame(data, columns=[i[0] for i in myvar.getvalue().description])
    print df
    

    以上代码的输出

                          COL1
    --------------------------
    0                   219586
    1                   246751
    2                   228245
    3                   244517
    4                   220765
    5                   243467
    6                   246622
    7                   222784
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-06
      • 2011-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多