jdbc calls the mysql stored procedure implementation code
- 2020-05-15 02:23:47
- OfStack
1. Create stored procedures
Create an MySQL stored procedure, add_pro
2. Call the stored procedure
Create an MySQL stored procedure, 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. Call the stored procedure
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(?,?,?)}"; // Calling stored procedure
CallableStatement cstm = connection.prepareCall(sql); // Instantiate object cstm
cstm.setInt(1, 122);
cstm.setInt(2, 2); //
cstm.registerOutParameter(3, Types.INTEGER); // Sets the return value type
cstm.execute(); // Executing stored procedures
System.out.println(cstm.getInt(3));
cstm.close();
connection.close();
}
}