1. CallableStatement
-
java.sql包
-
用于执行 SQL 存储过程的接口
-
继承自PreparedStatement
public interface CallableStatement extends PreparedStatement
2. 调用没有返回值的存储过程
2.1 存储过程
create or replace procedure test_a(param1 in varchar2, param2 in varchar2)
as
begin
insert into Dept(deptno,dname) values(param1, param2);
end;
2.2 代码实现
Connection conn = ConnectionUtil.getConnection();
CallableStatement cstmt = null;
try {
int deptNo = 26;
String dname = "dname26";
//实例化
cstmt = conn.prepareCall("{call test_a(?,?)}");
//设置参数
cstmt.setInt(1, deptNo);
cstmt.setString(2, dname);
//执行
int i = cstmt.executeUpdate();
System.out.println("影响行数:"+i);
} catch (Exception e) {
e.printStackTrace();
} finally {
ConnectionUtil.closeCallableStatement(cstmt);
ConnectionUtil.closeConnection(conn);
}
3. 调用有返回值的存储过程
3.1 存储过程
此存储过程通过传入的参数(Name),返回一个参数(address)。
create or replace procedure demo_procedure(namedemo in varchar2,addressdemo out varchar2)
as
begin
select address into addressdemo from system.demo where name=namedemo;
end;
2.2 代码实现
Connection conn = ConnectionUtil.getConnection();
CallableStatement cstmt = null;
try {
cstmt = conn.prepareCall("{ call dem_procedure(?,?) }");
cstmt .setString(1, "kalision");
cstmt .registerOutParameter(2, Types.VARCHAR); // 注册输出参数
cstmt .execute();
String testPrint = cstmt .getString(2);
System.out.println("存储过程返回的值是:"+testPrint);
} catch (Exception ex) {
ex2.printStackTrace();
} finally{
ConnectionUtil.closeCallableStatement(cstmt);
ConnectionUtil.closeConnection(conn);
}