java 调用存储过程-oracle

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);//注册 输出值的类型
 

具体代码如下 示:

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();
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值