JDBC 调用存储过程和自定义函数 CallableStatement

CallableStatement
调用存储过程,或者自定义函数的操作对象

  • {?=call<procedure -name >[( < arg1 >,, …)]} //调用自定义函数的语法
  • {call<procedure -name >[( < arg1 >,, …)]} //调用存储过程的语法

实例1: 调用存储过程,在数据库中删除表中的指定的值

步骤一:在数据库中写存储过程

delimiter $$
create procedure testPro(in num int,out r int )
  begin
     delete from emp where empno=num;
     select count(*) into r from emp;
  end $$

步骤二:调用存储过程

public class JDBCDemo3 {
   public static void main(String[] args) throws SQLException, ClassNotFoundException {
       //如何在程序里面调用存储过程或者自定义函数
       Connection conn = JDBCUtils.getConnection();
       String sql="{call testPro(?,?)}"; //输入或输出参数用?占位
       CallableStatement prepareCall = conn.prepareCall(sql);
       //给输入参数设置值
       prepareCall.setInt(1,7369);
       //如果有输出参数我们需要注册输出参数
       prepareCall.registerOutParameter(2, Types.INTEGER);
       boolean b = prepareCall.execute();
       //获取输出结果
       int r = prepareCall.getInt(2);
       System.out.println(r);
       //释放资源
       JDBCUtils.close(conn,prepareCall);
   }
}

实例2: 调用自定义函数,在数据库中删除表中的指定的值

步骤一:在数据库中写自定义函数

 delimiter $$
 create
    function 'mydb'.'testFun'(num int)
    returns int
    
    begin
    declare i int;
    delete from emp where empno=num;
    select count(*) into i from emp;
    
    return i;
    
    end$$
    
  delimiter;

步骤二:调用自定义函数

public class JDBCDemo4 {
 public static void main(String[] args) throws SQLException, ClassNotFoundException {
     Connection conn = JDBCUtils.getConnection();
     //调用自定义函数的语法
     //{?=call<procedure -name >[( < arg1 >,<arg2 >, ...)]}
     String sql="{?=call testFun(?)}";
     CallableStatement callableStatement = conn.prepareCall(sql);
     //设置输入参数
     callableStatement.setInt(2,7902);
     //注册返回值
     callableStatement.registerOutParameter(1, Types.INTEGER);
     callableStatement.execute();
     //获取返回的结果
     int r = callableStatement.getInt(1);
     System.out.println("结果是:"+r);
     //释放资源
     JDBCUtils.close(conn,callableStatement);

 }
}
发布了56 篇原创文章 · 获赞 6 · 访问量 7777

猜你喜欢

转载自blog.csdn.net/ly823260355/article/details/88812186