pl/sql基础知识—过程快速入门

n  过程

过程用于执行特定的操作,当建立过程时,既可以指定输入参数(in),也可以指定输出参数(out),通过在过程中使用输入参数,可以将数据传递到执行部分;通过使用输出参数可以将执行部分的数据传递到应用环境,在sqlplus中可以使用create procedure命令来建立过程。

实例如下:

①请考虑编写一个过程,可以输入雇员名,新工资,可修改雇员的工资

②如何调用过程有两种方法:

exec过程名(参数值…)

call  过程名(参数值…)

n  过程的进一步讲解

oracle过程,可以指定参数是输入的参数还是输出的参数,基本语法如下:

create procedure 过程名(变量名 in 变量类型…,变量名 out 变量类型…) is

//定义变量

begin                                                          

//执行语句;                                                   

end;      

 

 

 

 

 

 

 

注意:变量如果没有写in,默认是输入in

       变量类型不要指定大小,

特别说明:当我们编写过程时,可以输入show error来显示具体的错误

SQL>   create or replace procedure pro5(in_ename in varchar2,in_newsal in number) is

  2    begin

  3      update emp set sal=in_newsal where ename=in_ename;

  4      end;

  5  /

Procedure created

SQL> exec pro5('SMITH',100);

PL/SQL procedure successfully completed

 

如何在java程序中调用过程

需求说明:使用java调用刚才写的过程

package com.lsz.test;

import java.sql.*;

public class TestProcedure {

      

       public static void main(String[] args) {

              Connection ct=null;

              CallableStatement cs=null;

              try {

                     Class.forName("oracle.jdbc.driver.OracleDriver");

                     ct=DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:ORCL","scott","tiger");

                     cs=ct.prepareCall("{call pro5(?,?)}");

                     cs.setString(1,"SMITH");

                     cs.setFloat(2,456.5f);

                     cs.execute();

              } catch (Exception e) {

                     e.printStackTrace();

              }finally{

                     try {

                           

                     } catch (Exception e2) {

                     }

              }

       }

}

对SQLHelper类升级,添加一个可以调用存储过程的方法

public static void executeProcedure(String sql,String[] parameters){

              try {

                     ct=DriverManager.getConnection(url,username,password);

                     cs=ct.prepareCall(sql);

                     if(parameters!=null&&!"".equals(parameters)){

                            for(int i=0;i<parameters.length;i++){

                                   cs.setString(i+1,parameters[i]);

                            }

                     }

                     cs.execute();

              } catch (Exception e) {

                     e.printStackTrace();

                     throw new RuntimeException(e.getMessage());

              }finally{

                     close(rs,cs,ct);

              }

       }

课堂小练习:编写一个过程,可以接受ID和薪水,更新薪水,如果ID不存在,需要在exception中捕获,并给出提示!需要在控制台和java程序中都调用

create or replace procedure pro1(v_empno number,v_sal number) is

begin

  update emp set sal=v_sal where empno=v_empno;

exception

  when no_data_found then

   dbms_output.put_line('你输入的编号有误!');

end;

以上代码不会出现异常,因为no_data_found是在select语句中使用的。

猜你喜欢

转载自www.cnblogs.com/fanweisheng/p/11114098.html