一、前言
存储过程Procedure是寄存在数据服务器上的一组SQL操作单元,通过将一组SQL写成存储过程,然后通过java程序传递参数并调用执行,这样可以减少与数据库的交互次数,从而提供程序效率,下面分别针对有无参数及有无返回结果集分别用代码示例说明(以oracle数据库为例),具体如下:
1.调用执行没有参数的存储过程
数据库创建存储过程脚本,如下:
create or replace procedure test1@b@@b@as @b@@b@begin@b@@b@ insert into tab_test values(1, abc );@b@end;
java调用代码如下:
Class.forName("oracle.jdbc.driver.OracleDriver");@b@Connection conn=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:test","test","123456");@b@CallableStatement stmt=conn.prepareCall("{call test1()}");@b@stmt.execute();@b@stmt.close();@b@conn.close();
2.调用执行有IN参数的存储过程
创建存储过程数据库脚本,如下:
create or replace procedure test2(param1 in number,param2 in char)@b@as@b@begin@b@ insert into tab_test values(param1,param2);@b@ @b@end;
java调用该存储过程代码示例,如下:
Class.forName("oracle.jdbc.driver.OracleDriver");@b@Connection conn=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:test","test","123456");@b@CallableStatement stmt=conn.prepareCall("{call test2(?,?)}");@b@stmt.setInt(1,111);@b@stmt.setString(2,"test");@b@stmt.execute();@b@stmt.close();@b@conn.close();
3.调用即有IN和OUT参数的存储过程
数据脚本:
create or replace procedure test3 (vlength in number,vwidth in number,alength out number)@b@@b@as@b@@b@begin @b@@b@ alength:=2*(vlength+vwidth);@b@end;
调用代码,如下:
Class.forName("oracle.jdbc.driver.OracleDriver");@b@Connection conn=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:test","test","123456");@b@CallableStatement stmt=conn.prepareCall("{call test3(?,?,?)}");@b@int i=0;@b@stmt.setInt(1,1024);@b@stmt.setString(2,768);@b@stmt.registerOutpParameter(3,Types.INTEGER);@b@stmt.execute();@b@i=stmt.getInt(3);@b@System.out.println(i);@b@stmt.close();@b@conn.close();
4.调用有返回结果记录集的存储过程
数据库脚本,如下:
create or replace package PKG_HOTLINE@b@is@b@ type HotlineCursorType is REF CURSOR;@b@ procedure getAllHotline(rs out HotlineCursorType);@b@end;@b@@b@create or replace package body PKG_HOTLINE@b@is @b@ procedure getAllHotline (rs out HotlineCursorType)@b@ is@b@ begin@b@ open rs for select * from hotline;@b@ end;@b@end;
调用代码,如下:
Class.forName("oracle.jdbc.driver.OracleDriver");@b@Connection conn=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:test","test","123456");@b@CallableStatement stmt=conn.prepareCall("{call PKG_HOTLINE.getAllHotline(?)}");@b@stmt.registerOutpParameter(1,OracleTypes.CURSOR);@b@stmt.execute();@b@ResultSet rs=((OracleCallableStatement)stmt).getCursor(1);@b@while(rs.next()){@b@ String country=rs.getString(1);@b@ String pno=rs.getString(2);@b@ System.out.println("country:"+country+" pno:"+pno);@b@}@b@stmt.close();@b@conn.close();