CallableStatement接口

一、用途

CallableStatement是Statement接口的子接口,可以接收过程的返回值,主要用于调用数据库中的存储过程。

二、常用方法

1.根据编号取出过程的返回值

int getInt(int parameterIndex) throws SQLException
float getFloat(int parameterIndex) throws SQLException

2.设置制定编号的内容

void setInt(String parameterName,int x) throws SQLException
void setFloat(String parameterName,float x) throws SQLException

3.设置返回值类型,需要使用Types类

void registerOutParameter(int parameterIndex,int sqlType) throws SQLException

在Types中定义了很多常量。例如,返回值的类型为int,则sqlType为:

Types.INTEGER

三、在MySQL中建立存储过程

DELIMITER //
DROP PROCEDURE myproc //
CREATE PROCEDURE myproc(IN p1 int,INOUT p2 int,OUT p3 int)
BEGIN
    SELECT P1,P2,P3;
    SET p1=1;
    SET p2=2;
    SET p3=3;
END
//

其中:

INT类型:默认的设置,只是将值传递进来。

INOUT类型:把值传递到过程之中,可以保留过程对此值得修改。

扫描二维码关注公众号,回复: 3321987 查看本文章

OUT类型:可以不用传递内容进来,过程中对此值得操作可以返回。

四、实例

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Types;
public class ProcDemo{
	//mysql数据库驱动
	public static final String DBDRIVER="com.mysql.cj.jdbc.Driver";
	//mysql数据库连接地址
	public static final String DBURL="jdbc:mysql://localhost:3306/mldn?useSSL=false&serverTimezone=UTC";
	//mysql连接用户名
	public static final String DBUSER="root";
	//mysql连接密码
	public static final String DBPASS="root";

	public static void main(String[] args) throws Exception{
		//1、加载数据库驱动
		Class.forName(DBDRIVER);
		//2、获取数据库连接
		Connection conn=DriverManager.getConnection(DBURL,DBUSER,DBPASS);
		//3、实例化CallableStatement对象,并进行操作
		String sql="{CALL myproc(?,?,?)}";
		CallableStatement cstmt=conn.prepareCall(sql);
		cstmt.setInt(1,70);
		cstmt.setInt(2,80);
		cstmt.registerOutParameter(2,Types.INTEGER);
		cstmt.registerOutParameter(3,Types.INTEGER);
		cstmt.execute();
		System.out.println("INOUT的返回值:"+cstmt.getInt(2));
		System.out.println("OUT的返回值:"+cstmt.getInt(3));
		//4、关闭数据库连接
		cstmt.close();
		conn.close();
	}
}

步骤:

1、加载数据库驱动

2、获取数据库连接

3、实例化CallableStatement对象,并进行操作

String sql="{CALL myproc(?,?,?)}";
CallableStatement cstmt=conn.prepareCall(sql);
cstmt.setInt(1,70);
cstmt.setInt(2,80);
cstmt.registerOutParameter(2,Types.INTEGER);
cstmt.registerOutParameter(3,Types.INTEGER);
cstmt.execute();
System.out.println("INOUT的返回值:"+cstmt.getInt(2));
System.out.println("OUT的返回值:"+cstmt.getInt(3));

4、关闭数据库连接

猜你喜欢

转载自blog.csdn.net/weixin_41027750/article/details/82793767