cx_oracle:可以调用callfunc返回列表吗?

时间:2011-11-08 09:13:09

标签: python oracle plsql cx-oracle

我正在尝试编写一个返回整数数组的PL / SQL函数,然后能够使用cx_Oracles callfunc调用它。我认为我的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获取此类函数的结果?这可能吗?

我发现了这个http://osdir.com/ml/python.db.cx-oracle/2005-06/msg00014.html,但我不知道如何使用它。当我将我的类型定义更改为:

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 个答案:

答案 0 :(得分: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()

阅读本部分内容 manual也很有用。