灯火互联
管理员
管理员
  • 注册日期2011-07-27
  • 发帖数41778
  • QQ
  • 火币41290枚
  • 粉丝1086
  • 关注100
  • 终身成就奖
  • 最爱沙发
  • 忠实会员
  • 灌水天才奖
  • 贴图大师奖
  • 原创先锋奖
  • 特殊贡献奖
  • 宣传大使奖
  • 优秀斑竹奖
  • 社区明星
阅读:3070回复:0

使用存储过程

楼主#
更多 发布于:2012-09-08 09:38


很多数据库都支持在数据库内部执行的函数。这种方法有几个好处,包括更快的性能和改进的安全性。这些函数称为存储过程。存储过程是用来封装SQL语句来完成一个完整的业务功能,类似于面向对象里面方法的概念。虽然它们通常是用SQL编写的,但也可以用数据库支持的任何编程语言编写。随着java语言日趋流行,几个数据库厂商---Oracle(Oracle数据库)和IBM(db2数据库)都起用了java语言创建存储过程,还可以在不同数据库之间移动存储过程。
存储过程可以支持三种类型的参数:IN,OUT和INOUT,这对于存储过程在数据库内部真正能做什么来说,带来了很大的灵活性。不管存储过程是用什么语言编写的,它都能以一种标准的方式从java应用程序调用。
首先,您需要创建一个CallableStatement对象。为了标识存储过程和过程需要的参数的类型和数量,还要允许使用三种类型的调用。下面的清单说明了这三种类型(假定我们正在调用一个名为StudentList的存储过程):
n {call StudentList}如果过程不需要参数
n {call StudentList(?,?)}如果过程需要两个参数
n {?=call StudentList(?,?)}如果参数需要两个参数并返回一个
要想使用存储过程,首先应该创建一个存储过程!

代码的实现
[java]
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.NamingException;

public class CreateStoredProceduresofSQLServer {
    public static void main(String[] args) {
        Connection con = null;
        Statement stmt = null;
        String jndiname = "jdbcPool/mydatasource";

        try {
            con = DBCon.getConnectionFromPooledDataSource(jndiname);
            stmt = con.createStatement();

            // 1.创建存储过程show_students  
            String createProcedure1 = "create procedure show_students " + "as " + "select id, name,age " + "from students " + "order by id";
            // 删除数据库中存在的同名过程  
            stmt.executeUpdate("if exists(select name from sysobjects "
                    + "where name='show_students'and type='p') "
                    + "drop procedure show_students");
            stmt.executeUpdate(createProcedure1);

            // 2.创建储存过程onestudent  
            String createProcedure2 = "create procedure onestudent "
                    + "@stu_id int = null, " + "@name varchar(20) output, "
                    + "@age  int  output " + "as " + "if @stu_id = null "
                    + "BEGIN "
                    + "  PRINT 'ERROR: You must specify a stu_id value.' "
                    + "  RETURN "
                    + "END "
                    +
                    // Get the sales for the specified cof_name and " +  
                    // assign it to the output parameter. " +  
                    "SELECT @name = name, @age = age " + "FROM coffees "
                    + "WHERE id = @stu_id " + "RETURN ";
            stmt.executeUpdate("if exists(select name from sysobjects "
                    + "where name='onestudent'and type='p') "
                    + "drop procedure onestudent");
            stmt.executeUpdate(createProcedure2);

            // 3.创建函数  
            String createProcedure3 = "CREATE FUNCTION pubuse.ageofstu "
                    +
                    // Input cof_name  
                    "(@stu_name varchar(20)) "
                    + "RETURNS int "
                    + // return sales  
                    "AS " + "BEGIN " + "  DECLARE @age int "
                    + "  SELECT @age = age " + "  FROM student "
                    + "  WHERE name like @stu_name " + "  RETURN @age "
                    + "END ";
            stmt.executeUpdate("if exists(select name from sysobjects "
                    + "where name='ageofstu') "
                    + "drop function pubuse.ageofstu");
            stmt.executeUpdate(createProcedure3);
            stmt.close();
            con.close();
        } catch (NamingException ex) {
            System.err.println("Name Not Bound : " + ex.getMessage());
        } catch (SQLException ex) {
            System.err.println("SQLException : " + ex.getMessage());
        }
        System.out.println("程序执行结束!");
    }
}
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import javax.naming.NamingException;
public class CreateStoredProceduresofSQLServer {
public static void main(String[] args) {
  Connection con = null;
  Statement stmt = null;
  String jndiname = "jdbcPool/mydatasource";
  try {
   con = DBCon.getConnectionFromPooledDataSource(jndiname);
   stmt = con.createStatement();
   // 1.创建存储过程show_students
   String createProcedure1 = "create procedure show_students " + "as " + "select id, name,age " + "from students " + "order by id";
   // 删除数据库中存在的同名过程
   stmt.executeUpdate("if exists(select name from sysobjects "
     + "where name='show_students'and type='p') "
     + "drop procedure show_students");
   stmt.executeUpdate(createProcedure1);
   // 2.创建储存过程onestudent
   String createProcedure2 = "create procedure onestudent "
     + "@stu_id int = null, " + "@name varchar(20) output, "
     + "@age  int  output " + "as " + "if @stu_id = null "
     + "BEGIN "
     + "  PRINT 'ERROR: You must specify a stu_id value.' "
     + "  RETURN "
     + "END "
     +
     // Get the sales for the specified cof_name and " +
     // assign it to the output parameter. " +
     "SELECT @name = name, @age = age " + "FROM coffees "
     + "WHERE id = @stu_id " + "RETURN ";
   stmt.executeUpdate("if exists(select name from sysobjects "
     + "where name='onestudent'and type='p') "
     + "drop procedure onestudent");
   stmt.executeUpdate(createProcedure2);
   // 3.创建函数www.atcpu.com
   String createProcedure3 = "CREATE FUNCTION pubuse.ageofstu "
     +
     // Input cof_name
     "(@stu_name varchar(20)) "
     + "RETURNS int "
     + // return sales
     "AS " + "BEGIN " + "  DECLARE @age int "
     + "  SELECT @age = age " + "  FROM student "
     + "  WHERE name like @stu_name " + "  RETURN @age "
     + "END ";
   stmt.executeUpdate("if exists(select name from sysobjects "
     + "where name='ageofstu') "
     + "drop function pubuse.ageofstu");
   stmt.executeUpdate(createProcedure3);
   stmt.close();
   con.close();
  } catch (NamingException ex) {
   System.err.println("Name Not Bound : " + ex.getMessage());
  } catch (SQLException ex) {
   System.err.println("SQLException : " + ex.getMessage());
  }
  System.out.println("程序执行结束!");
}
}
下面是使用存储过程的代码:
[cpp]
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import javax.naming.NamingException;

public class InvokeStoreProcdureofSQLServer {
    public static void main(String[] args) {
        Connection con = null;
        String jndiname = "jdbcPool/mydatasource";
        // 定义调用存储过程和函数的 SQL 语句  
        String callSQL1 = "{call show_students}";
        String callSQL2 = "{call onestudent(?,?,?)}";
        String callSQL3 = "{? = call ageofstu(?)}";

        try {
            con = DBCon.getConnectionFromPooledDataSource(jndiname);
            // 调用第 1 个存储过程  
            CallableStatement cs = con.prepareCall(callSQL1);
            ResultSet rs = cs.executeQuery();
            System.out.println("第一个存储过程调用结果");
            while (rs.next()) {
                String id = rs.getString(1);
                String name = rs.getString(2);
                String age = rs.getString(3);
                System.out.println(id + "  " + name + " " + age);
            }
            // 调用第 2 个存储过程  
            cs = con.prepareCall(callSQL2);
            cs.setString(1, "2");
            cs.registerOutParameter(2, Types.CHAR);
            cs.registerOutParameter(3, Types.INTEGER);
            cs.execute();
            String name = cs.getString(2);
            int age = cs.getInt(3);
            System.out.println("第二个存储过程调用结果");
            System.out.println("This student's name is " + name
                    + " and age is " + age);
            // 调用函数  
            cs = con.prepareCall(callSQL3);
            cs.setString(2, "小罗");
            cs.registerOutParameter(1, Types.INTEGER);
            cs.execute();
            age = cs.getInt(1);
            System.out.println("函数调用结果");
            System.out.println("This student's name is " + age + ".");
            cs.close();
            con.close();
        } catch (NamingException ex) {
            System.err.println("Name Not Bound : " + ex.getMessage());
        } catch (SQLException ex) {
            System.err.println("SQLException : " + ex.getMessage());
        }
        System.out.println("调用结束!");
    }
}


喜欢0 评分0
游客

返回顶部