1. 建立預存程序
建立一個MySQL的預存程序 add_pro
複製代碼 代碼如下:delimiter //
drop procedure add_pro //
create procedure add_pro(a int , b int , out sum int )
begin
set sum = a * b;
end;
//
2. 調用預存程序 複製代碼 代碼如下:package com.zhanggaosong;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Types;
public class CallableStatementTest {
public static final String DRIVER_CLASS = "com.mysql.jdbc.Driver";
public static final String URL = "jdbc:mysql://127.0.0.1:3306/test";
public static final String USERNAME = "root";
public static final String PASSWORD = "123456";
public static void main(String[] args) throws Exception {
Class.forName(DRIVER_CLASS);
Connection connection = DriverManager.getConnection(URL, USERNAME,
PASSWORD);
String sql = "{CALL add_pro(?,?,?)}"; //調用預存程序
CallableStatement cstm = connection.prepareCall(sql); //執行個體化對象cstm
cstm.setInt(1, 122);
cstm.setInt(2, 2); //
cstm.registerOutParameter(3, Types.INTEGER); // 設定傳回值類型
cstm.execute(); // 執行預存程序
System.out.println(cstm.getInt(3));
cstm.close();
connection.close();
}
}