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();
}
}