使用存储过程 (一)

2014-11-24 07:29:09 · 作者: · 浏览: 4

很多数据库都支持在数据库内部执行的函数。这种方法有几个好处,包括更快的性能和改进的安全性。这些函数称为存储过程。存储过程是用来封装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.