標籤:
以對錶test進行增,刪,改,查進行說明:
1.建立表test
create table TEST
(
TID NUMBER not null,
TNAME VARCHAR2(32),
TCODE VARCHAR2(32),
CREATEDATE DATE
)
alter table TEST
add constraint PK_TEST_ID primary key (TID)
2.資料庫中預存程序的指令碼:
create or replace package test_package is
procedure test_add(pid number,pcode varchar2,pname varchar2,pcreatedate date);
procedure test_update(pid number,pname varchar2);
procedure getNameAndCodeById(pid number,pcode out varchar2,pname out varchar2);
function getNameById(pid number) return varchar2;
end test_package;
create or replace package body test_package is
/*
向表中增加一條資料
*/
procedure test_add(pid number,pcode varchar2,pname varchar2,pcreatedate date)is
begin
insert into test values(pid,pcode,pname,pcreatedate);
commit;
end;
/*
將表中tid為pid的資料的tname更新為pname
*/
procedure test_update(pid number,pname varchar2)is
begin
update test set tname=pname where tid=pid;
commit;
end;
/*
根據ID尋找對應的code和name
*/
procedure getNameAndCodeById(pid number,pcode out varchar2,pname out varchar2)is
begin
select t.tcode,t.tname into pcode,pname from test t where t.tid=pid;
end;
/*
根據ID尋找對應的name
*/
function getNameById(pid number) return varchar2 is
returnValue varchar2(100) :=‘‘;
begin
select t.tname into returnValue from test t where t.tid=pid;
return returnValue;
end;
end test_package;
3.在java程式中調用預存程序
A.通過預存程序向表中添加一條資料
public void add() throws Exception
{
Connection con=new Condb().getConnection();
String sql="{call test_package.test_add(?,?,?,?)}";
// sql也可以寫為 "begin test_package.test_add(?,?,?,?);end;"
CallableStatement stmt=con.prepareCall(sql);
stmt.setInt(1, 1);
stmt.setString(2, "test");
stmt.setString(3, "test");
//注意日期類型的處理
stmt.setDate(4, new Date(new java.util.Date().getTime()));
stmt.execute();
stmt.close();
con.close();
}
B.通過給定的tid更新這條資料的tname欄位
public void update() throws Exception
{
Connection con=new Condb().getConnection();
String sql="{call test_package.test_update(?,?)}";
CallableStatement stmt=con.prepareCall(sql);
stmt.setInt(1, 1);
stmt.setString(2, "update");
stmt.execute();
stmt.close();
con.close();
}
C.調用預存程序根據給定的tid返回tcode和tname
public void getNameAndCodeById() throws Exception
{
String tcode="";
String tname="";
Connection con=new Condb().getConnection();
String sql="{call test_package.getNameAndCodeById(?,?,?)}";
CallableStatement stmt=con.prepareCall(sql);
stmt.setInt(1, 1);
stmt.registerOutParameter(2, Types.VARCHAR);
stmt.registerOutParameter(3, Types.VARCHAR);
stmt.execute();
tname=stmt.getString(2);
tcode=stmt.getString(3);
System.out.println("tname="+tname+",tcode="+tcode);
stmt.close();
con.close();
}
D.通過調用函數根據給定的tid返回tname
public void getNameById() throws Exception
{
String tname="";
Connection con=new Condb().getConnection();
String sql="select test_package.getNameById(?) from dual";
CallableStatement stmt=con.prepareCall(sql);
stmt.setInt(1, 1);
ResultSet rs=stmt.executeQuery();
while(rs.next())
{
tname=rs.getString(1);
}
System.out.println("name="+tname);
stmt.close();
con.close();
}
java調用預存程序和函數