Mysql存储过程(Java)

这是我学习mysql存储过程时关心的几个点内容,希望能对你们学习存储过程有所帮助。

语法:

create procedure sp_name ([proc_parameter[,...]])

[characteristic ...]
begin
.......
end

Proc_parameter:存储过程的参数列表,多个参数彼此间用逗号分隔
      格式[IN|OUT|INOUT] param_name type

  IN(输入参数)、OUT(输出参数)、INOUT(输出参数和输入);

      Param_name为参数名;

  type为参数的数据类型。

Characteristic:用于描述存储特征

存储过程使用逻辑语法:

逻辑判断:

1、if判断

  IF expression THEN commands

    [ELSEIF expression THEN commands]

    [ELSE commands]

    END IF; 

2、case判断

  CASE case_expression

    WHEN when_expression THEN commands

    WHEN when_expression THEN commands

    ELSE commands

    END CASE;

循环判断:

1、WHILE……DO……END WHILE
2、REPEAT……UNTIL END REPEAT
3、LOOP……END LOOP
4、GOTO

Java对存储过程操作

1、获取存储过程输出值

--存储过程SQL
create
procedure tb_pro(out op int) begin set op = 10 end

java操作:

CallableStatement cs = con.prepareCall(sql);
cs.registerOutParameter(1, java.sql.Types.INTEGER);//注册存储过程的out型参数类型;使用之前必须注册;
cs.execute();
System.out.println(cs.getInt(2)); //获取out的输出结果

2、获取查询结果集(来自select查询),且有多个结果集如何处理?

-- 存储过程SQL
create
procedure bach_pro() begin select * from table1; select * from table2; end

java操作:

 CallableStatement cs = con.prepareCall(sql);
 cs.execute();
 ResultSet resultSet = cs.getResultSet();
        
 //遍历第一个结果集
 while(resultSet.next()){            
     System.out.println(resultSet.getInt(1)); // 输出结果集
 }
       
 //获取下一个结果集 
 ResultSet rs2;
 while(cs.getMoreResults()){
      rs2 = cs.getResultSet();
      while (rs2.next()) {
          System.out.println(rs2.getInt(1)); //输出结果集列
      }
 }

3、当我们要在存储过程中处理查询结果集时,我们就需要使用到cursor,下面是cursor一个简单的使用例子

begin
declare stop int default 0 ;--需要在cursor前声明参数
declare id_temp int; 
declare cur1 cursor for (select id from xinguan);
declare continue handler for not found set stop = 1; --声明cursor扫描完后设置值,用于结束循环
open cur1;
cur1_loop:loop
    fetch cur1 into id_temp;  --从cursor中取值赋给变量
    if stop then
        leave cur1_loop;
    end if;
end loop cur1_loop;
close cur1;
end
posted @ 2017-03-11 23:08  Rainbean  阅读(1973)  评论(0编辑  收藏  举报