- 相關(guān)推薦
Java中調(diào)用Oracle包的過程
在Java中調(diào)用Oracle包是我們程序員經(jīng)常遇到的事情,那么它具體的過程是怎么樣的呢?我們一起來看看!
一、先在oracle中編寫測試過程
1、首選建一個(gè)測試表
-- Create table
create table BOOK
(
BOOKID VARCHAR2(50) not null,
BOOKNAME VARCHAR2(50) not null,
PUBLISHER VARCHAR2(50) not null,
PRICE VARCHAR2(50) null
)
2、編寫ORACLE測試過程
CREATE OR REPLACE PACKAGE pkg_test
AS
TYPE myrctype IS REF CURSOR;
PROCEDURE get (p_id VARCHAR2, p_str OUT VARCHAR2, p_rc OUT myrctype);
END pkg_test;
/
CREATE OR REPLACE PACKAGE BODY pkg_test
AS
PROCEDURE get (p_id VARCHAR2, p_str OUT VARCHAR2,p_rc OUT myrctype)
IS
sqlstr VARCHAR2 (500);
BEGIN
p_str := ''''Hello,may~'''';
IF p_id = ''''all'''' THEN
OPEN p_rc FOR
SELECT *
FROM BOOK;
ELSE
sqlstr :=
''''select *
from BOOK where BOOKID=:w_id'''';
OPEN p_rc FOR sqlstr USING p_id;
END IF;
END get;
END pkg_test;
/
在這里我們建立了一個(gè)輸入?yún)?shù),為普通類型,兩個(gè)輸出參數(shù),其中一個(gè)為普通VARCHAR2型,另一個(gè)為特殊的記錄集類型。
(注:在數(shù)據(jù)庫端測試一下這個(gè)過程,以確保沒有問題,開始下面的操作~:)
二、編寫JAVA代碼測試過程
/*
* 創(chuàng)建日期: 2003-8-8
*/
package JDBC;
/**
* 作者:may
* 時(shí)間:15:09:23
*/
import java.sql.*;
import oracle.jdbc.driver.*;
public class proctest {
public static void main(String[] args) {
proctest pc = new proctest();
pc.ShowContent();
}
String sDBDriver="oracle.jdbc.driver.OracleDriver";
String sConnStr="jdbc:oracle:thin:@10.3.8.48:1521:ORADB";
Connection connect=null;
ResultSet rs = null;
public proctest(){
try{
Class.forName(sDBDriver);
}
catch(ClassNotFoundException e){
System.err.println(e.getMessage());
}
}
public ResultSet ShowContent()
{
try{
connect = DriverManager.getConnection(sConnStr,"SHUIBJ","SHUIBJ");
CallableStatement stmt = connect.prepareCall("{call PKG_TEST.GET(?,?,?)}");
stmt.setString(1,"all"); //輸入?yún)?shù)
stmt.registerOutParameter(2,Types.CHAR); //輸出參數(shù)為普通參數(shù)
stmt.registerOutParameter(3,OracleTypes.CURSOR); //輸出參數(shù)為結(jié)果集參數(shù)
stmt.executeQuery();
rs = ((OracleCallableStatement) stmt).getCursor(3); //得到輸出結(jié)果集參數(shù)
ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
String str = stmt.getString(2);
System.out.println("第二個(gè)參數(shù)為:"+str);
System.out.println("結(jié)果集列數(shù)"+numberOfColumns);
//列出結(jié)果集中的記錄
ResultSetMetaData md = rs.getMetaData();
int nColumns = md.getColumnCount();
for (int i=1;i<=nColumns;i++){
System.out.print(md.getColumnName(i)+((i==nColumns)?"\n":"\t"));
if(i==2) System.out.print("\t");
}
while (rs.next()){
for(int i=1;i<=nColumns;i++){
System.out.print(rs.getString(i)+((i==nColumns)?"\n":"\t"));
}
}
}
catch(SQLException ex){
System.err.println(ex.getMessage()+"連數(shù)據(jù)庫有問題!");
}
return rs;
}
}
輸出結(jié)果為:
第二個(gè)參數(shù)為:Hello,may~
結(jié)果集列數(shù)4
BOOKID BOOKNAME PUBLISHER PRICE
001-22-23-1 jsp 應(yīng)用開發(fā)詳解 電子工業(yè)出版社 123
123 uml參考手冊 機(jī)械工業(yè)出版社 34