Java调用存储过程,与传统CRUD编程差不多,在传统CRUD中执行SQL的对象是 PreparedStatement,
由 ResultSet 来接收查询结果;但是调用 存储过程,负责执行过程的是 CallableStatement;
也由它来获得结果集;
此外,与PreparedStatement还有一点不同的是,设置查询参数时,不是之前那样->
PreparedStatement ps = new PreparedStatement();
ps.setInt(1,22);
ps.setString(2,'luxury');
而是改为:
CallableStatement cs = new CallableStatement();
cs = con.prepareCall("call getExpire(?,?)");//第一个?:传递参数;第二个?:输出参数
cs.setInt(1,8);
cs.registerOutParameter(2, java.sql.Types.INTEGER);//注册 输出值的类型
由 ResultSet 来接收查询结果;但是调用 存储过程,负责执行过程的是 CallableStatement;
也由它来获得结果集;
此外,与PreparedStatement还有一点不同的是,设置查询参数时,不是之前那样->
PreparedStatement ps = new PreparedStatement();
ps.setInt(1,22);
ps.setString(2,'luxury');
而是改为:
CallableStatement cs = new CallableStatement();
cs = con.prepareCall("call getExpire(?,?)");//第一个?:传递参数;第二个?:输出参数
cs.setInt(1,8);
cs.registerOutParameter(2, java.sql.Types.INTEGER);//注册 输出值的类型
具体代码如下 示:
package com.bdc;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
/**
* Java 连接 Oracle 存储过程
* Procedure-
* create or replace procedure getExpire(id in number default 7,getexpire out varchar2)
as
begin
select expire into getexpire from weibo_account where accountid=id;
end;
* @author lu
*
*/
public class ConnectionProcedure {
private Connection con = null;
private CallableStatement cs = null;
private Properties properties = new Properties();
private FileInputStream fs = new FileInputStream("src/oracle.properties");
private String driver;
private String url;
private String user;
private String passwd;
public ConnectionProcedure() throws IOException {
properties.load(fs);
this.driver = properties.getProperty("driver");
this.url = properties.getProperty("url");
this.user = properties.getProperty("user");
this.passwd = properties.getProperty("passwd");
doProcedure();
}
/**
* 处理连接存储过程
*/
private void doProcedure() {
System.out.println("===connection is begin====");
try {
Class.forName(driver);
System.out.println("====driver is ok====");
con = DriverManager.getConnection(url,user,passwd);
System.out.println("====connection is ok====");
//调用 名为 count 的存储过程,其中 有一个 in 类型输入参数 和 一个 out 类型输出参数
cs = con.prepareCall("call getExpire(?,?)");
//设置 输入 参数类型 和 值
cs.setInt(1, 7);
//设置 输出 参数类型
cs.registerOutParameter(2, java.sql.Types.INTEGER);
//执行存储过程
cs.execute();
//获得 out 输出值
int expire = cs.getInt(2);输出值 在 第二个 ? 号
System.out.println("the expire = " + expire);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
new ConnectionProcedure();
}
}