存储过程

存储过程

1.在数据库中使用存储过程(存储过程的创建DBA)

 

#无参的存储过程
delimiter $$ 
 create procedure pro1()
 begin
     select * from stu ;
 end ;
 $$

#带输入参数的存储过程
 create procedure pro2(in a int)
 begin
    select * from stu where id = a ;
 end ;
 $$

delimiter $$
create procedure pro3(in a int,in b int)
begin
    select a + b ;
end ;
$$
delimiter ;

delimiter $$
create procedure pro4(in n int)
begin
    select * from t3 where id =  n ;
end ;
$$
delimiter ;

#创建带输出参数的存储过程
 delimiter $$
 create procedure pro5(in a int,out b varchar(20))
 begin
     select name into b from stu where id = a ;
 end ;
 $$

call pro5(1,@n) ;
select @n ;

#创建带多个输出参数的存储过程
 delimiter $$
  create procedure pro6(in a int,out b varchar(20),out c int)
 begin
      select name,age into b,c from stu where id = a ;
 end ;
 $$

select @name,@age $$

 

 

2.在JDBC中调用存储过程

package com.hcx.jdbc;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.Types;

import org.junit.Test;

import com.hcx.utils.JdbcUtils;
//演示JDBC调用存储过程
public class ProcedureTest {

	//执行不带返回值的存储过程没有任何任意
	@Test
	public void testPro2() throws Exception {
		// 获得链接对象
		Connection conn = JdbcUtils.getConnection();
		// 创建执行存储过程的命令对象
		CallableStatement cstmt = conn.prepareCall("{call pro2(?)}") ;
		//指定?的值
		cstmt.setInt(1, 1) ;
		//执行存储过程
		cstmt.execute() ;
		
		// 释放资源
		JdbcUtils.release(null, cstmt, conn);
	}
	
	@Test
	public void testPro5() throws Exception {
		// 获得链接对象
		Connection conn = JdbcUtils.getConnection();
		// 创建执行存储过程的命令对象
		CallableStatement cstmt = conn.prepareCall("{call pro5(?,?)}") ;
		//指定?的值
		cstmt.setInt(1, 1) ;
		//指定第二个?是输出参数
		cstmt.registerOutParameter(2, Types.VARCHAR) ;
		
		//执行存储过程
		cstmt.execute() ;
		
		//获得返回值
		String name = cstmt.getString(2) ;
		System.out.println(name);
		
		// 释放资源
		JdbcUtils.release(null, cstmt, conn);
	}
}

 


 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值