转http://bbs.csdn.net/topics/300115606
第一步:写你的存储过程
delimiter //
create procedure test_proc ()
begin
select * from test_table1 where id=1;
select * from test_table2 where id=2;
select * from test_table3 where id=3;
end;
//
delimiter ;
call test_proc()这样就可以返回三个结果集,每个结果集对应一个select。
那么在JAVA程序里面如何来取得这三个结果集呢?!
这样做:
boolean bl = false;
ResultSet = null;
Connection con = new Connection();
con="得到一个有效的连接"
String strSql="{CALL test_proc()}";
CallableStatement cstm=con.prepareCall(strSql);
bl=cstm.execute();----若存储过程被正常执行,并至少有一个结果集返回,则bl=true;否则就会是bl=false;
while(bl){
rs=cstm.getResultSet();---取得第一个结果集
if(rs.next){
System.out.println(rs.getInt(1));----打印出结果集的第一个字段
}
bl=cstm.getMoreResultSet();----继续去取结果集,若还还能取到结果集,则bl=true了。然后回去循环。
}
这样,就可以循环把结果集处理了,注意存储过程中每个SELECT都返回一个结果集,查询中的处理方式就是如上。
这是最科学的处理方式。
转http://www.xue5.com/Developer/Java/677461.html
MySQL数据库中有两个表,一个student,一个teacher
其中student表结构如下
teacher表如下
有存储过程checkAll
BEGIN
select * from teacher;
SELECT * FROM student;
END
Java代码如下
1 public static Map<String,Object>getAll(){ 2 Connection conn=null; 3 CallableStatement cs=null; 4 ResultSet rs=null; 5 Map<String,Object> map=new HashMap<String, Object>(); 6 Map<String,String> temp=null; 7 List<Map<String,String>> list=null; 8 try { 9 conn=DBCon.getInstance(); 10 cs=conn.prepareCall("{call checkAll()}"); 11 cs.execute(); 12 rs=cs.getResultSet(); 13 if(rs!=null){ 14 list=new ArrayList<Map<String,String>>(); 15 while(rs.next()){ 16 temp=new HashMap<String, String>(); 17 temp.put("id", rs.getInt("id")+""); 18 temp.put("birthday", rs.getDate("birthday")+""); 19 temp.put("name", rs.getString("name")+""); 20 temp.put("title", rs.getString("title")+""); 21 list.add(temp); 22 } 23 map.put("teacher", list); 24 if(cs.getMoreResults()){ 25 rs=cs.getResultSet(); 26 list=new ArrayList<Map<String,String>>(); 27 while(rs.next()){ 28 temp=new HashMap<String, String>(); 29 temp.put("id", rs.getInt("id")+""); 30 temp.put("name", rs.getString("name")); 31 temp.put("age", rs.getInt("age")+""); 32 list.add(temp); 33 } 34 map.put("student", list); 35 } 36 } 37 } catch (Exception e) { 38 e.printStackTrace(); 39 } 40 finally{ 41 DbUtils.closeQuietly(conn, cs, rs); 42 } 43 return map; 44 }
若是数据库是SqlServer,存储过程涉及到表的更新(增、删、改)的话会出错,可以在存储过程里面加上一句:set nocount on即可