当前位置: 移动技术网 > IT编程>数据库>Oracle > Oracle存储过程和自定义函数详解

Oracle存储过程和自定义函数详解

2017年12月08日  | 移动技术网IT编程  | 我要评论

张惠雅,梁汉文图片,2012年的好歌

概述

pl/sql中的过程和函数(通常称为子程序)是pl/sql块的一种特殊的类型,这种类型的子程序可以以编译的形式存放在数据库中,并为后续的程序块调用。

相同点: 完成特定功能的程序

不同点:是否用return语句返回值。

举个例子:

create or replace procedure printstudents(p_staffname in xgj_test.username%type) as

 cursor c_testdata is
 select t.sal, t.comm from xgj_test t where t.username = p_staffname;

begin

 for v_info in c_testdata loop
 dbms_output.put_line(v_info.sal || ' ' || v_info.comm);
 end loop;

end printstudents;

一旦创建了改程序并将其存储在数据库中,就可以使用如下的方式调用该过程

begin
 printstudents('computer science');
 printstudents('match');
end;
/

或者

exec printstudents('computer science');
exec printstudents('match');

在命令窗口中:

在pl/sql工具的sql窗口中:

存储过程的创建和调用

基本语法

create [ or replace] procedure procedure_name
[( argument [ {in | out | in out }] type,
......
argument [ {in | out | in out }] type ) ] { is | as}
procedure_body

无参的存储过程

/**
 无参数的存过
 打印hello world

 调用存储过程:
 1. exec sayhelloworld();
 2 begin 
 sayhelloworld();
 end;
 /

*/
create or replace procedure sayhelloworld
as
--说明部分
begin
 dbms_output.put_line('hello world');
end sayhelloworld;

调用过程:

sql> set serveroutput on ;
sql> exec sayhelloworld();

hello world

pl/sql procedure successfully completed

sql> begin
 2 sayhelloworld();
 3 sayhelloworld();
 4 end;
 5 /

hello world
hello world

pl/sql procedure successfully completed

带参数的存储过程

/**
创建一个带参数的存储过程

给指定的员工增加工资,并打印增长前后的工资

*/
create or replace procedure addsalary(staffname in xgj_test.username%type )
as
--定义一个变量保存调整之前的薪水
oldsalary xgj_test.sal%type;

begin
 --查询员工涨之前的薪水
 select t.sal into oldsalary from xgj_test t where t.username=staffname; 

 --调整薪水
 update xgj_test t set t.sal = sal+1000 where t.username=staffname ;

 --输出
 dbms_output.put_line('调整之前的薪水:'|| oldsalary || ' ,调整之后的薪水:' || (oldsalary + 1000));

end addsalary;

可以看到,update语句之后并没有commit的操作。

一般来讲为了保证事务的一致性,由调用者来提交比较合适,当然了是需要区分具体的业务需求的~

begin 
addsalary('xiao');
addsalary('gong');
commit ;
end ;
/

存储函数

基本语法

create [ or replace] function function_name
[( argument [ {in | out | in out }] type,
......
argument [ {in | out | in out }] type ) ] 
return { is | as}
function_body

其中 return子句是必须存在的,一个函数如果没有执行return就结束将发生错误,这一点和存过有说不同。

存储函数

准备的数据如下:

/**
查询员工的年薪 (月工资*12 + 奖金)
*/

create or replace function querysalaryincome(staffname in varchar2)

 return number as
 --定义变量保存员工的工资和奖金
 psalary xgj_test.sal%type;
 pcomm xgj_test.comm%type;

begin
 --查询员工的工资和奖金
 select t.sal, t.comm
 into psalary, pcomm
 from xgj_test t
 where t.username = staffname;
 --直接返回年薪
 return psalary * 12 + pcomm;
end querysalaryincome;

存在一个问题,当奖金为空的时候,算出来的年收入竟然是空的。

因为 如果一个表达式中有空值,那么这个表达式的结果即为空值。

所以我们需要对空值进行处理, 使用nvl函数即可。

最后修改后的function为

create or replace function querysalaryincome(staffname in varchar2)

 return number as
 --定义变量保存员工的工资和奖金
 psalary xgj_test.sal%type;
 pcomm xgj_test.comm%type;

begin
 --查询员工的工资和奖金
 select t.sal, t.comm
 into psalary, pcomm
 from xgj_test t
 where t.username = staffname;
 --直接返回年薪
 return psalary * 12 + nvl(pcomm,0);
end querysalaryincome;

out参数

一般来讲,存储过程和存储函数的区别在于存储函数可以有一个返回值,而存储过程没有返回值。

  • 存储过程和存储函数都可以有out参数
  • 存储过程和存储函数都可以有多个out参数
  • 存储过程可以通过out参数实现返回值

那我们如何选择存储过程和存储函数呢?

原则:

如果只有一个返回值,用存储函数,否则(即没有返回值或者有多个返回值)使用存储过程。

/**
根据员工姓名,查询员工的全部信息
*/
create or replace procedure querystaffinfo(staffname in xgj_test.username%type,
           psal out number,
           pcomm out xgj_test.comm%type,
           pjob out xgj_test.job%type) 

is

begin
 --查询该员工的薪资,奖金和职位
 select t.sal,t.comm,t.job into psal,pcomm,pjob from xgj_test t where t.username=staffname;
end querystaffinfo;


先抛出两个思考问题:

  • 查询员工的所有信息–> out参数太多怎么办?
  • 查询某个部门中所有员工的信息–> out中返回集合?

后面会讲到如何解决? 总不能一个个的写out吧~

在应用中访问存储过程和存储函数

概述

我们使用java程序连接oracle数据库。

使用jar: ojdbc14.jar

关于oracle官方提供的几个jar的区别

  • classes12.jar (1,600,090 bytes) - for use with jdk 1.2 and jdk 1.3
  • classes12_g.jar (2,044,594 bytes) - same as classes12.jar, except that classes were compiled with “javac -g” and contain some tracing information.
  • classes12dms.jar (1,607,745 bytes) - same as classes12.jar, except that it contains additional code`to support oracle dynamic monitoring service.
  • classes12dms_g.jar (2,052,968 bytes) - same as classes12dms.jar except that classes were compiled with “javac -g” and contain some tracing information.
  • ojdbc14.jar (1,545,954 bytes) - classes for use with jdk 1.4 and 1.5
  • ojdbc14_g.jar (1,938,906 bytes) - same as ojdbc14.jar, except that classes were compiled with “javac -g” and contain some tracing information.
  • ojdbc14dms.jar (1,553,561 bytes) - same as ojdbc14.jar, except that it contains additional code`to support oracle dynamic monitoring service.
  • ojdbc14dms_g.jar (1,947,136 bytes) - same as ojdbc14dms.jar, except that classes were compiled with “javac -g” and contain some tracing information.

工程目录如下:

简单的写下获取数据库连接的工具类

import java.sql.connection;
import java.sql.drivermanager;
import java.sql.resultset;
import java.sql.sqlexception;
import java.sql.statement;

public class dbutils {

 // 设定数据库驱动,数据库连接地址端口名称,用户名,密码
 private static final string driver = "oracle.jdbc.driver.oracledriver";
 private static final string url = "jdbc:oracle:thin:@ip:xxxx";
 private static final string username = "xxxx";
 private static final string password = "xxxx";

 /**
  * 注册数据库驱动
  */
 static {
  try {
   class.forname(driver);
  } catch (classnotfoundexception e) {
   throw new exceptionininitializererror(e.getmessage());
  }
 }

 /**
  * 获取数据库连接
  */
 public static connection getconnection() {
  try {
   connection connection = drivermanager.getconnection(url, username, password);
   // 成功,返回connection
   return connection;
  } catch (sqlexception e) {
   e.printstacktrace();
  }
  // 获取失败,返回null
  return null;
 }

 /**
  * 释放连接
  */
 public static void cleanup(connection conn, statement st, resultset rs) {

  if (rs != null) {
   try {
    rs.close();
   } catch (sqlexception e) {
    e.printstacktrace();
   } finally {
    rs = null;
   }
  }

  if (st != null) {
   try {
    st.close();
   } catch (sqlexception e) {
    e.printstacktrace();
   } finally {
    st = null;
   }
  }

  if (conn != null) {
   try {
    conn.close();
   } catch (sqlexception e) {
    e.printstacktrace();
   } finally {
    conn = null;
   }
  }

 }
}

在应用程序中访问存储过程

根据官方提供的api,我们可以看到:

import java.sql.callablestatement;
import java.sql.connection;
import java.sql.sqlexception;

import org.junit.test;

import com.turing.oracle.dbutil.dbutils;

import oracle.jdbc.oracletypes;


public class testprocedure {

 @test
 public void callprocedure(){
  // {call <procedure-name>[(<arg1>,<arg2>, ...)]}

  connection conn = null ;
  callablestatement callablestatement = null ;

  /**
   *
   根据员工姓名,查询员工的全部信息
   create or replace procedure querystaffinfo(staffname in xgj_test.username%type,
              psal out number,
              pcomm out xgj_test.comm%type,
              pjob out xgj_test.job%type) 
   is
   begin
    --查询该员工的薪资,奖金和职位
    select t.sal,t.comm,t.job into psal,pcomm,pjob from xgj_test t where t.username=staffname;
   end querystaffinfo;
   */
  // 我们可以看到该存过 4个参数 1个入参 3个出参
  string sql = "{call querystaffinfo(?,?,?,?)}";

  try {
   // 获取连接
   conn = dbutils.getconnection();
   // 通过连接获取到callablestatement
   callablestatement = conn.preparecall(sql);

   // 对于in 参数,需要赋值
   callablestatement.setstring(1, "xiao");
   // 对于out 参数,需要声明
   callablestatement.registeroutparameter(2, oracletypes.number); // 第二个 ?
   callablestatement.registeroutparameter(3, oracletypes.number);// 第三个 ?
   callablestatement.registeroutparameter(4, oracletypes.varchar);// 第四个 ?

   // 执行调用
   callablestatement.execute();

   // 取出结果
   int salary = callablestatement.getint(2);
   int comm = callablestatement.getint(3);
   string job = callablestatement.getstring(3);

   system.out.println(salary + "\t" + comm + "\t" + job);

  } catch (sqlexception e) {
   e.printstacktrace();
  }finally {
   dbutils.cleanup(conn, callablestatement, null);
  }


 }
}

在应用程序中访问存储函数

根据官方提供的api,我们可以看到:

import java.sql.callablestatement;
import java.sql.connection;

import org.junit.test;

import com.turing.oracle.dbutil.dbutils;

import oracle.jdbc.oracletypes;

public class testfuction {

 @test
 public void callfuction(){
  //{?= call <procedure-name>[(<arg1>,<arg2>, ...)]}
  connection conn = null;
  callablestatement call = null;
  /**
   * create or replace function querysalaryincome(staffname in varchar2)
     return number as
     --定义变量保存员工的工资和奖金
     psalary xgj_test.sal%type;
     pcomm xgj_test.comm%type;

    begin
     --查询员工的工资和奖金
     select t.sal, t.comm
     into psalary, pcomm
     from xgj_test t
     where t.username = staffname;
     --直接返回年薪
     return psalary * 12 + nvl(pcomm,0);
    end querysalaryincome;
   */

  string sql = "{?=call querysalaryincome(?)}";

  try {
   // 获取连接
   conn = dbutils.getconnection();
   // 通过conn获取callablestatement
   call = conn.preparecall(sql);

   // out 参数,需要声明
   call.registeroutparameter(1, oracletypes.number);
   // in 参数,需要赋值
   call.setstring(2, "gong");

   // 执行
   call.execute();
   // 取出返回值 第一个?的值
   double income = call.getdouble(1);
   system.out.println("该员工的年收入:" + income);
  } catch (exception e) {
   e.printstacktrace();
  }finally {
   dbutils.cleanup(conn, call, null);
  }
 }

}

在out参数中访问光标

在out参数中使用光标

我们之前抛出的两个思考问题:

  • 查询员工的所有信息–> out参数太多怎么办?
  • 查询某个部门中所有员工的信息–> out中返回集合?

我们可以通过返回cursor的方式来实现。

在out参数中使用光标 的步骤:

  • 申明包结构
  • 包头
  • 包体

包头:

create or replace package mypackage is

 -- author : administrator
 -- created : 2016-6-4 18:10:42
 -- purpose : 

 -- 使用type关键字 is ref cursor说明是cursor类型
 type staffcursor is ref cursor;

 procedure querystaffjob(pjob   in xgj_test.job%type,
       jobstafflist out staffcursor);

end mypackage;

创建完包头之后,创建包体,包体需要实现包头中声明的所有方法。

包体

create or replace package body mypackage is

 procedure querystaffjob(pjob   in xgj_test.job%type,
       jobstafflist out staffcursor)

 as
 begin
  open jobstafflist for select * from xgj_test t where t.job=pjob;
 end querystaffjob;

end mypackage;

事实上,通过plsql工具创建包头,编译后,包体的框架就会自动的生成了。

在应用程序中访问包下的存储过程

在应用程序中访问包下的存储过程

在应用程序中访问包下的存储过程 ,需要带包名

import java.sql.callablestatement;
import java.sql.connection;
import java.sql.resultset;

import org.junit.test;

import com.turing.oracle.dbutil.dbutils;

import oracle.jdbc.oracletypes;
import oracle.jdbc.driver.oraclecallablestatement;

public class testcursor {

 @test
 public void testcursor(){
  /**
   * 
   * create or replace package mypackage is
     type staffcursor is ref cursor;

     procedure querystaffjob(pjob   in xgj_test.job%type,
           jobstafflist out staffcursor);

    end mypackage;
   */
  string sql = "{call mypackage.querystaffjob(?,?)}" ;

  connection conn = null;
  callablestatement call = null ;
  resultset rs = null;

  try {
   // 获取数据库连接
   conn = dbutils.getconnection();
   // 通过conn创建callablestatemet
   call = conn.preparecall(sql);

   // in 参数 需要赋值
   call.setstring(1, "staff");
   // out 参数需要声明
   call.registeroutparameter(2, oracletypes.cursor);

   // 执行调用
   call.execute();

   // 获取返回值
   rs = ((oraclecallablestatement)call).getcursor(2);
   while(rs.next()){
    // 取出值
    string username = rs.getstring("username");
    double sal = rs.getdouble("sal");
    double comm = rs.getdouble("comm");

    system.out.println("username:" + username + "\t sal:" + sal + "\t comm:" + comm);
   }
  } catch (exception e) {
   e.printstacktrace();
  }finally {
   dbutils.cleanup(conn, call, rs);
  }
 }

}

原文链接:http://blog.csdn.net/yangshangwei/article/details/51581952

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网