天天看點

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

}