java 调用mysql的存储过程(简单示例)
首先我在mysql的test数据库里定义了一个student表:
create table student4(
id int primary key,
sanme char(5)
);
插入几个数据做测试用:
inset into student values(1,'mayi');
inset into student values(2,'mayi');
inset into student values(3,'mayi');
建立存储过程:
in 型:
delimiter //
create procedure demo_in(in p_in int)
begin
select p_in;
set p_in=2;
select p_in;
end;
//
delimiter ;
java测试代码:
CallableStatement callstatement = conn.prepareCall("call demo_in(?)");//conn,数据库连接
callstatement.setInt(1, 1);//设置第一个参数
callstatement.execute();//执行
conn.close();//关闭连接
out型:
delimiter //
create procedure demo_out(out s int)
begin
select count(*) into s from student;
end
//
delimiter ;
java测试代码:
CallableStatement callstatement = conn.prepareCall("call demo_out(?)");
callstatement.registerOutParameter(1, java.sql.Types.INTEGER);//注册存储过程的out型参数类型;使用之前必须注册;
callstatement.execute();//执行
System.out.println(callstatement.getInt(1));//获得存储过程的输出参数
conn.close();//关闭连接
总结: 先在数据库中建立存储过程,然后获得数据库连接conn后,生成CallableStatement对象,执行相应的操作。