0

我得到了一个可以调用如下的函数,即使用“SQL Oracle Developer”:

--set serveroutput on size 2000;
declare
    theId VARCHAR(20);
    theKey VARCHAR(20) := '';
    theName VARCHAR(20) := '';
    theEmail VARCHAR(20) := '';
    theDob DATE := '';
    theVal NUMBER;
begin
    theId := Package.FunctionName(
        theKey,
        theName,
        theEmail,
        theDob,
        theVal
    );
    --DBMS_OUTPUT.PUT_LINE(theId);
    --DBMS_OUTPUT.PUT_LINE(theKey);
    --DBMS_OUTPUT.PUT_LINE(theVal);
    exception
        when others then
            RAISE;
end;

现在,我应该使用 cx_Oracle 在 Python 中调用这个函数。

为此,我尝试了以下方法,但无法使其正常工作:

cursor = connection.cursor()
function = '''
    BEGIN
        theKey := inout_theKey;
        theName := in_theName;
        theEmail := in_theEmail;
        theDob := in_theDob;
        theVal := out_theVal;
        theId := Package.FunctionName(theKey, theName theEmail, theDob, theVal)
        :out_theId := theId;
        :inout_theKey := theKey;
        :out_theVal := theVal;
    END;'''

out_theId = cursor.var(str)
out_theVal = cursor.var(int)
inout_theKey = cursor.var(str)
inout_theKey.setvalue(0, '')
cursor.execute(
    function, 
    inout_theKey=inout_theKey, 
    in_theName='', 
    in_theEmail='', 
    in_theDob='', 
    out_theId=out_theId, 
    out_theVal=out_theVal)
_logger.debug(out_theId.getvalue())

这失败并出现错误:

cx_Oracle.DatabaseError: ORA-01036: illegal variable name/number

也许有人可以指出我的绑定不正确的正确方向?


对于它的价值,我还尝试将 DECLARE 语句添加到 function ,即

function = '''
    DECLARE 
       theId VARCHAR(20) := out_theId;  
       theKey VARCHAR(20) := inout_ttheKey; 
       theName VARCHAR(20) := in_theName; 
       theEmail VARCHAR(20) := in_theEmail; 
       theDob DATE := in_theDob; 
       theVal NUMBER := out_theVal;  
    BEGIN  

       theId := Package.FunctionName(theKey, theName, theEmail, theDob, theVal); 

       :out_theId := theId; 
       :inout_theKey := theKey; 
       :out_theVal := theVal; 
    END;'''

它仍然为我提供了相同的结果(illegal variable name/number)。

通过 cx_Oracle 与数据库的连接正在工作(使用其他几个 sql 语句验证)。

4

1 回答 1

0

显然有一个相当简单的解决方案:

cursor = connection.cursor()
function = 'Package.FunctionName'

inout_theKey = ''
in_theName = ''
in_theEmail = ''
in_theDob = ''
out_theVal = cursor.var(int)  # default type is str, else define the type like this

out_theId = cursor.callfunc(function, str, [
    inout_theKey, 
    in_theName, 
    in_theEmail, 
    in_theDob, 
    out_theVal
])

_logger.debug(out_theId)
_logger.debug(inout_theKey)
_logger.debug(out_theVal)

本质上,您只需要根据调用的函数定义提供函数名称 ( function)、预期的返回值(str在这种情况下)以及 IN、OUT 和 IN/OUT 参数列表callfunc

参考:https ://cx-oracle.readthedocs.io/en/latest/api_manual/cursor.html#Cursor.callfunc和https://cx-oracle.readthedocs.io/en/latest/user_guide/plsql_execution.html# plsqlfunc

于 2021-09-27T22:26:15.743 回答