使用 IN、OUT、IN/OUT 参数和 Python 中的 return 值调用 Oracle DB 函数

Calling an Oracle DB function with IN, OUT, IN/OUT parameters and return value in Python

我得到了一个可以调用如下的函数,即使用 '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 = '''
    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 语句验证)。

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

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)、预期的 return 值(在本例中为 str)以及 IN、OUT 和 IN/OUT 参数根据 callfunc 调用的函数定义。

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