mysql存储过程实例
mysql存储过程实例
由于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());
}
}
}