2011-11-08 58 views
0

我想寫一個PL/SQL函數,它返回一個整數數組,然後可以用cx_Oracles callfunc調用它。我認爲我的PL/SQL功能正確,但我不知道如何用cx_Oracle調用它。cx_oracle:可以callfunc返回列表嗎?

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

東西在的線,

import cx_Oracle 

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

conn_data = str('%s/%[email protected]%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,這部分也將是有益的。

+0

該行中的return_value:'execute_func = cursor.callfunc('test_function',return_value,[20])'未定義。它應該是什麼? – Maciek

+0

Mea culpa, 我已經將它編輯爲out_parameter,因爲它應該是。 –

+0

不幸的是,這是行不通的。我得到 >>> execute_func = cursor.callfunc( 'test_function',out_parameter,[20]) 回溯(最近通話最後一個): 文件 「」,1號線,在 cx_Oracle.DatabaseError:ORA-06550 :行1,列13: PLS-00382:表達式類型錯誤 ORA-06550:第1行第7列: PL/SQL:語句被忽略 – Maciek