由於mysql自定義函數中不能輸出兩或多個結果,所以需要用到mysql的存儲過程。
下面是一個例子。
sql語句:
DROP PROCEDURE IF EXISTS `testguocheng`;
CREATE PROCEDURE `testguocheng`(IN `sql1` varchar(100),IN `sql2` varchar(100))
BEGIN
SET @SQLStr1=CONCAT(sql1 );
PREPARE stmt1 from @SQLStr1 ;
EXECUTE stmt1;
SET @SQLStr2=CONCAT(sql2);
PREPARE stmt2 from @SQLStr2 ;
EXECUTE stmt2;
END;
解釋一下這個存儲過程,輸入的是兩個sql語句,得到的結果是兩個結果集。
下面是調用的java語句。
public static void getData() {
Connection conn = JdbcUtils.getConnection();
CallableStatement stmt = null;
ResultSet rs=null;
try{
stmt = conn.prepareCall("{call testguocheng('select * from tsys_user;','select count(*) from tsys_user;')}");
boolean flag=stmt.execute();
int i=0;
while(flag){
System.out.println("第幾個結果集"+(++i));
rs = stmt.getResultSet();
if(i==1){
while(rs.next()){
System.out.println("uid:" +rs.getString("uid")+",uname:"+rs.getString("uname"));
}
}else{
while(rs.next()){
System.out.println("總數:" +rs.getString(1));
}
}
flag=stmt.getMoreResults();
}
}catch(Exception e){
System.out.println(e.toString());
}finally{
try {
stmt.close();
conn.close();
}catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}