如何在SQLALCHEMY中将复杂的Oracle UserDefinedType作为存储过程的输出

时间:2018-05-24 17:40:36

标签: sql oracle sqlalchemy

我在Oracle中有2个用户定义的DataTypes,我在存储过程的输出中使用它。如何使用SQLALCHEMY和打印输出调用此proc?我尝试创建一个types.UserDefinedType子类并使用它绑定结果参数但我不断收到错误,表示cx_oracle不支持此类型

Create or replace TYPE type1 as Object (
      param1 NUMBER(15,0),
      param2 clob);
/
create or replace TYPE t_type1 as TABLE OF type1;
/
create or replace PROCEDURE "DO_SOMETHING" (
      results OUT t_type1,
      status OUT CHAR,
      status_msg OUT VARCHAR2)

下面是我试图用来调用Stored proc之上的代码。如果在oracle中存储了proc用户定义数据类型的proc,我如何绑定一个pram?

connection = engine.connect()
try:
    proc_query = text(
        "begin DO_SOMETHING(:results,:status, :status_msg); end;",
        bindparams=[outparam('results', <WHAT TO PUT HERE>, outparam('status', CHAR),
                    outparam('status_msg', VARCHAR)])
    result = connection.execute(proc_query)
    status_code = result.out_parameters['results'].strip()
    err_nbr = result.out_parameters['status']
    err_msg = result.out_parameters['status_msg'].strip()
except Exception as e:
    logging.exception(e)
    print("Error occured in refresh_view" ,e)
    raise e
finally:
    connection.close()

1 个答案:

答案 0 :(得分:0)

I tweaked a little to use VARCHAR2 instead of CLOB to make life easier :)
But this should help - 

CREATE OR REPLACE TYPE TYPE1 AS OBJECT (
      PARAM1 NUMBER(15,0),
      PARAM2 VARCHAR2(1024));
/


CREATE OR REPLACE TYPE T_TYPE1 AS TABLE OF TYPE1;
/


CREATE OR REPLACE PROCEDURE DO_SOMETHING (
      RESULTS OUT T_TYPE1,
      STATUS OUT CHAR,
      STATUS_MSG OUT VARCHAR2) AS
BEGIN
    STATUS_MSG :='STATUS_MSG';
    STATUS := '1';
    RESULTS := T_TYPE1(TYPE1(13,'MESSAGE'));
END;
/
  

致电 -

SET SERVEROUT ON;
DECLARE
    RESULTS T_TYPE1;
    STATUS CHAR;
    MSG VARCHAR2(1024);
BEGIN
    DO_SOMETHING(RESULTS, STATUS, MSG);
    DBMS_OUTPUT.PUT_LINE(STATUS||','|| MSG);
    DBMS_OUTPUT.PUT_LINE(RESULTS(1).PARAM1);
    DBMS_OUTPUT.PUT_LINE(RESULTS(1).PARAM2);
END;
/
  

输出 -

1,STATUS_MSG
13
MESSAGE