当前位置:文档之家› mysql存储过程.详细说明,java代码调用过程

mysql存储过程.详细说明,java代码调用过程

Mysql存储过程调用
说明:
由括号包围的参数列必须总是存在。

如果没有参数,也该使用一个空参数列()。

每个参数默认都是一个IN参数。

要指定为其它参数,可在参数名之前使用关键词OUT或INOUT
在mysql客户端定义存储过程的时候使用delimiter命令来把语句定界符从;变为//。

当使用delimiter命令时,你应该避免使用反斜杠(‘"’)字符,因为那是MySQL的转义字符。

1、创建过程格式:
Mysql> drop procedure if exists user_findById;
Mysql> delimiter //
Create procedure user_findById(in n int)
Begin
Select * from user where id= n;
End
//
调用过程:
Mysql> set @n=1; --定义变量
Call user_findById(@n);--调用过程
// --显示结果
======================================================
例2:
Mysql> drop procedure if exists user_count;
Mysql> delimiter //
Create procedure user_count(out count int)
Begin
Select count(*) into count from user;
End
// --结束
注意:
MySQL存储过程
“in”参数:
跟 C语言的函数参数的值传递类似, MySQL存储过程内部可能会修改此,参数,但对 in类型参数的修改,对调用者(caller)来说是不可见的(not visible)。

“out”参数:
从存储过程内部传值给调用者。

在存储过程内部,该参数初始值为 null,无论调用者是否给存储过程参数设置值inout参数跟 out类似,都可以从存储过程内部传值给调用者。

不同的是:调用者还可以通过 inout参数传递值给存储过程。

总结:如果仅仅想把数据传给MySQL存储过程,那就使用“in”类型
参数;如果仅仅从MySQL存储过程返回值,那就使用“out”类型参数;如果需要把数据传给MySQL存储过程,还要经过一些计算后再传回给我们,
此时,要使用“inout”类型参数。

JAVA中调用过程:
/**
* 调用过程cal_ning,计算class_id班的最高成绩和名字 * @param class_id 班号
*/
public static void callProc(int class_id){
String sql = "{call cal_ning(?,?,?)}";
//获得连接
Connection conn = null;
CallableStatement stmt = null;
//构造语句对象,传递过程及参数,返回结果
try{
conn = ConnectionUtils.getConnection();// 工具类获得连接
stmt = conn.prepareCall(sql);
//输入参数,
stmt.setInt(1, class_id);
//注册输出参数的位置和类型
stmt.registerOutParameter(2, Types.CHAR);
stmt.registerOutParameter(3, Types.INTEGER);
//执行
stmt.execute();
//取出过程运行的结果,指定输出参数的位置
String name = stmt.getString(2);
int score = stmt.getInt(3);
System.out.println(name.trim() + " : " + score); }catch(Exception e){
e.printStackTrace();
}finally{
//关闭资源
ConnectionUtils.close(stmt);
ConnectionUtils.close(conn);
}
例2:
/**
* 调用过程ProcLogin_ning,输入两个参数,返回结果
* @param id 考生id
* @param pwd 考生密码
* @return 成功:1; id正确,pwd错:0; 没有id: -1
*/
public static int login(int id, String pwd){ int flag = -1;
String sql = "{call proclogin_ning(?,?,?) }";
Connection conn = null;
CallableStatement stmt = null;
try{
conn = ConnectionUtils.getConnection();
stmt = conn.prepareCall(sql);
stmt.setInt(1, id);
stmt.setString(2, pwd);
stmt.registerOutParameter(3, Types.INTEGER);
stmt.execute();
flag = stmt.getInt(3);
}catch(Exception e){
e.printStackTrace();
}finally{
ConnectionUtils.close(stmt);
ConnectionUtils.close(conn);
}
return flag;
}。

相关主题