天天看点

java 调用存储过程-oracle

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

}