Connection。CallableStatement 的 OUT/INOUT 參數調用 registerOutParameter。prepareCall("{call proc_name(?,?,?)}") 準備,設輸入參數,execute(),再取輸出值。import java.sql.*;
public class TestCallProc {
public static void main(String[] args) {
String url = "jdbc:db2://wellhope/sample";
String user = "db2admin";
String pwd = "db2admin";
try {
Class.forName("COM.ibm.db2.jdbc.Net.DB2Driver").newInstance();
Connection con = DriverManager.getConnection(url, user, pwd);
con.setAutoCommit(false);
// 準備調用 PRO_YHDL1(IN VARCHAR, IN VARCHAR, OUT INTEGER)
CallableStatement cs = con.prepareCall("{call PRO_YHDL1(?,?,?)}");
cs.registerOutParameter(3, Types.INTEGER); // 註冊第3個參數為 OUT INTEGER
cs.setString(1, "123"); // 輸入參數1
cs.setString(2, "123"); // 輸入參數2
cs.execute();
int result = cs.getInt(3); // 獲取輸出參數
System.out.println("存儲過程返回: " + result);
cs.close();
con.close();
} catch (SQLException ex) {
while (ex != null) {
System.err.println("SQLState: " + ex.getSQLState());
System.err.println("Message: " + ex.getMessage());
System.err.println("Vendor: " + ex.getErrorCode());
ex = ex.getNextException();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
DB2 支援 Java、SQL PL 等語言編寫存儲過程。以下為 Java 實現的 PRO_YHDL1:驗證用戶 ID/密碼,匹配則返回 1,否則 0。
import java.sql.*;
public class Pro_yhdl1 {
public static void pro_yhdl1(String m_id, String m_pwd, int[] result)
throws SQLException, Exception {
// 使用默認連接(服務端上下文)
Connection con = DriverManager.getConnection("jdbc:default:connection");
PreparedStatement stmt = null;
ResultSet rs = null;
try {
String sql = "SELECT PWD FROM DB2ADMIN.YHDL WHERE ID = ?";
stmt = con.prepareStatement(sql);
stmt.setString(1, m_id.trim());
rs = stmt.executeQuery();
String dbPwd = "";
if (rs.next()) {
dbPwd = rs.getString(1);
if (rs.wasNull()) dbPwd = "";
else dbPwd = dbPwd.trim();
}
result[0] = dbPwd.equals(m_pwd.trim()) ? 1 : 0;
} finally {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (con != null) con.close();
}
}
}
COM.ibm.db2.jdbc.Net.DB2Driver(Type 3),新版建議用 com.ibm.db2.jcc.DB2Driver(Type 4,JCC 驅動)。int[]、String[])接收,標量無法帶回值。jdbc:default:connection 表示復用當前會話連接,無需重新認證。SQLException,需用 getNextException() 遍歷。function/jar 目錄,執行 CALL SQLJ.INSTALL_JAR(...) 註冊,再 CREATE PROCEDURE ... EXTERNAL NAME 'class.method' LANGUAGE JAVA PARAMETER STYLE JAVA 定義。掌握 CallableStatement 三步驟、OUT 參數用數組接收、服務端用 jdbc:default:connection,即可高效調用 DB2 存儲過程。建議新項目統一遷移至 JCC Type 4 驅動,簡化配置並提升性能。