oracle11g的程序包

程序包中的相關解釋

程序包: 對 變量、函數、過程、遊標、異常和對象的封裝。
優點:把相關的內容放在一起。
程序包的組成:由包規範和包主體兩部分組成。
規範(包頭):公共對象的聲明 變量、常量、異常、過程、函數、遊標規範等等的聲明。
主體(包體):私有對象的聲明私有類型的聲明以及包頭內過程、函數的實現。

創建包頭、包體的語法: body之分

包頭 包體
CREATE [OR REPLACE] PACKAGE CREATE [OR REPLACE] PACKAGE BODY
package_name IS or AS package_name IS or AS
[Public item declarations] [Private item declarations]
END [package_name]; END [package_name];

公有對象:在包頭內聲明的變量,出了這個包還能使用。
私有對象:出了這個包我就不能使用了,僅僅我能用。

1、舉例創建:

create or replace package  pack1 
 is 
   a int := 9 ;                          -- 公有變量
   procedure insert_student(a1  in student%rowtype );   --聲明過程
   procedure update_student(a2  in student%rowtype );
 end pack1;
 /  
 create or replace package body pack1 
 is 
   b int := 6 ;                          -- 私有變量
   procedure insert_student(a1  in student%rowtype );   --過程定義1
   is
   begin
      insert into student(sno,sname,sage)  values (a1.sno ,a1.sname,a1.sage);
      commit;
      dbms_output.put_line(pack1.b);     --內部調用可以執行
   end  insert_student;
   procedure update_student(a2  in student%rowtype );   --過程定義2
    is
   begin
      update student set sname =a2.sname where sno=a2.sno ;
      commit;
   end  update_student;    
 end pack1;
 /

程序包的使用:
declare
  a1  student%rowtype ;
begin
  a1.sno:=1;
  a1.sname:='Jack';
  a1.sage:=20;
  pack1.insert_student(a1);
 end;
 /

判斷變量範圍:
execute  dbms_output.put_line(pack1.a);        --可以執行
execute  dbms_output.put_line(pack1.b);        --不可以執行

2、程序包的優點
在做項目的時候都是先建立程序包,再在程序包內建立相關過程與函數
模塊化
更輕鬆的應用程序設計
信息隱藏
新增功能
性能更佳

3、在程序包中寫遊標
注意包頭內聲明遊標、在包體中定義遊標、在過程中使用遊標的方法。

顯示遊標
 
 create or replace package pack2   -- 包頭部分
 is
   cursor mycursor return student%rowtype;   -- 指明return
   procedure mycursor_use ;    -- 聲明過程
  end pack2;
  /
 create or replace package body  pack2   --包體部分
 is
   cursor mycursor return student%rowtype is select * from student;   --注意statement
   procedure mycursor_use   
   is 
      stu_rec  student%rowtype;
      open mycursor;
      fetch mycursor into stu_rec;
      while mycursor%found loop
           dbms_output.putline('sno='||stu_rec.sno);
           fetch mycursor  into  stu_rec;
        end  loop;
        close mycursor;
    end mycursor_use;
  end pack2;
  /

exec pack2.mycursor_use;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章