cx_oracle: callfunc能返回列表吗?

1 投票
1 回答
4012 浏览
提问于 2025-04-17 05:51

我正在尝试写一个PL/SQL函数,这个函数会返回一个整数数组,然后我想用cx_Oracle来调用它。我觉得我的PL/SQL函数写得没问题,但我不知道怎么用cx_Oracle来调用它。

create or replace type test_type is table of NUMBER(10);

create or replace function test_function (n in INTEGER)
RETURN test_type
AS
  tmp_tab test_type := test_type();
BEGIN
  tmp_tab.EXTEND(n);
  FOR i IN 1 .. n LOOP
    tmp_tab(i) := i;
  END LOOP;
  RETURN tmp_tab;
END;

在sqlplus中可以正常工作:

SQL> select test_function(20) from dual;

TEST_FUNCTION(20)
--------------------------------------------------------------------------------
TEST_TYPE(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)

我该如何使用cx_Oracle来获取这个函数的结果呢?这可能吗?

我找到这个链接,但我不太知道怎么用它。当我把我的类型定义改成:

create or replace type test_type is table of NUMBER(10) index by binary_integer;

我收到的提示是:警告:类型创建时有编译错误。

SQL> sho err
Errors for TYPE TEST_TYPE:

LINE/COL ERROR
-------- -----------------------------------------------------------------
0/0  PL/SQL: Compilation unit analysis terminated
1/19     PLS-00355: use of pl/sql table not allowed in this context

1 个回答

1

大概是这样的,

import cx_Oracle

db_sid = 'db_sid'
db_usr = 'schema'
db_pwd = 'passwd'

conn_data = str('%s/%s@%s') % (db_usr, db_pwd, db_sid)

try:
    db = ora.connect(conn_data)
    except ora.DatabaseError, e:
    error, = e
    ORAmessage = error.message.rstrip("\n")
    print "DatabaseError: %s" % ORAmessage
else:
    cursor = db.cursor()
    try:
        out_parameter = cursor.var(cx_Oracle.NUMBER)
        # calling function to retrieve results until 20
        execute_func  = cursor.callfunc('test_function', out_parameter, [20])
        print str(return_value.getvalue())
    except ora.DatabaseError, exc:
        error, = exc
        ORAmessage = error.message.rstrip("\n")
        print "DatabaseError: %s" % ORAmessage
    cursor.close()

db.close()

阅读这部分内容的手册也会很有帮助。

撰写回答