OceanBase 使用 CallableStatements 調(diào)用存儲(chǔ)過(guò)程

2021-06-30 15:46 更新

OceanBase Connector/J 的 CallableStatement 接口支持調(diào)用存儲(chǔ)過(guò)程。

CallableStatement 支持使用 executeUpdate(),executeQuery() 或 execute() 方法調(diào)用 Statement 執(zhí)行存儲(chǔ)過(guò)程。其中最靈活的調(diào)用方法是 execute(),因?yàn)槟鸁o(wú)需提前知道存儲(chǔ)過(guò)程是否返回結(jié)果集。

如下為一個(gè)存儲(chǔ)過(guò)程示例,該存儲(chǔ)過(guò)程返回以 1 遞增的 inOutParam 值,以及使用 inputParam 作為 ResultSet 來(lái)輸入字符串。

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

根據(jù)如下步驟調(diào)用上述示例中的 obSp 存儲(chǔ)過(guò)程:

  1. 通過(guò)使用 Connection.prepareCall() 準(zhǔn)備可調(diào)用語(yǔ)句。

    示例如下:

    import java.sql.CallableStatement;
    
    ...
    
    
    
        CallableStatement cSt = conn.prepareCall("{call obSp(?, ?)}");
    
    
        cSt.setString(1, "asdfg");
  2. 注冊(cè)輸出參數(shù)(如果存在)

    為了檢索輸出參數(shù)的值(在創(chuàng)建存儲(chǔ)過(guò)程時(shí)指定為 OUT 或 INOUT 的參數(shù)),OceanBase Connector/J 要求在執(zhí)行語(yǔ)句之前使用 CallableStatement 接口中的 registerOutputParameter() 方法指定輸出參數(shù)的值。示例如下:

    import java.sql.Types;
    ...
        cSt.registerOutParameter(2, Types.INTEGER);
    
        cSt.registerOutParameter("inOutParam", Types.INTEGER);
    ...
  3. 設(shè)置輸入?yún)?shù)(如果存在)。

    輸入和輸入/輸出參數(shù)的設(shè)置與 PreparedStatement 對(duì)象相同。但是,CallableStatement 也支持按名稱設(shè)置參數(shù)。示例如下:

         cSt.setString(1, "asdfg");
    
         cSt.setString("inputParam", "asdfg");
    
    
         cSt.setInt(2, 1);
    
         cSt.setInt("inOutParam", 1);
    
    ...
  4. 執(zhí)行 CallableStatement,并檢索任何結(jié)果集或輸出參數(shù)。

    示例如下:

    ...
    
        boolean obResults = cSt.execute();
    
           while (obResults) {
            ResultSet rs = cSt.getResultSet();
    
    
            ...
    
            obResults = cSt.getMoreResults();
        }
    
        int outputValue = cSt.getInt(2); 
    
        outputValue = cSt.getInt("inOutParam"); 
    
    ...
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)