jdbc调用mysql存储过程实现代码

网络编程 2021-07-05 15:27www.168986.cn编程入门
接下来将介绍下mysql存储过程的创建及调用,调用时涉及到jdbc的知识,不熟悉的朋友还要温习下jdbc哦,话不多说看代码,希望可以帮助到你
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 .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 = ".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();
}
}

Copyright © 2016-2025 www.168986.cn 狼蚁网络 版权所有 Power by