OceanBase Connector/J 的CallableStatement接口支持调用存储过程。

CallableStatement支持使用executeUpdate()executeQuery()execute()方法调用 Statement 执行存储过程。其中最灵活的调用方法是execute(),因为您无需提前知道存储过程是否返回结果集。

如下为一个存储过程示例,该存储过程返回以 1 递增的inOutParam值,以及使用inputParam作为ResultSet来输入字符串。

CREATE PROCEDURE obSp(IN inputParam VARCHAR(100),                        INOUT inOutParam INT)BEGIN    DECLARE n INT;    SET n = inOutParam + 1;    SET inOutParam = n;    SELECT inputParam;    SELECT CONCAT('zhang', inputParam);END

根据如下步骤调用上述示例中的obSp存储过程:

    通过使用Connection.prepareCall()准备可调用语句。

    示例如下:

    import java.sql.CallableStatement;...    CallableStatement cSt = conn.prepareCall("{call obSp(?, ?)}");    cSt.setString(1, "asdfg");

    注册输出参数(如果存在)

    为了检索输出参数的值(在创建存储过程时指定为OUTINOUT的参数),OceanBase Connector/J 要求在执行语句之前使用CallableStatement接口中的registerOutputParameter()方法指定输出参数的值。示例如下:

    import java.sql.Types;...    cSt.registerOutParameter(2, Types.INTEGER);    cSt.registerOutParameter("inOutParam", Types.INTEGER);...

    设置输入参数(如果存在)。

    输入和输入/输出参数的设置与PreparedStatement对象相同。但是,CallableStatement也支持按名称设置参数。示例如下:

         cSt.setString(1, "asdfg");     cSt.setString("inputParam", "asdfg");     cSt.setInt(2, 1);     cSt.setInt("inOutParam", 1);...

    执行CallableStatement,并检索任何结果集或输出参数。

    示例如下:

    ...    boolean obResults = cSt.execute();       while (obResults) {        ResultSet rs = cSt.getResultSet();        ...        obResults = cSt.getMoreResults();    }    int outputValue = cSt.getInt(2);     outputValue = cSt.getInt("inOutParam"); ...