注册

最新文章 | 栏目列表 | 文章搜索

所有栏目 - 电子商务类
Java调用SQL Server的存储过程详解
欢迎到博客http://blog.csdn.net/java2000_net/archive/2008/04/21/2311956.aspx查看

包含了如下几部分

使用不带参数的存储过程
使用带有输入参数的存储过程
使用带有输出参数的存储过程
使用带有返回状态的存储过程
使用带有更新计数的存储过程

1使用不带参数的存储过程


使用 JDBC 驱动程序调用不带参数的存储过程时,必须使用 call SQL 转义序列。不带参数的 call 转义序列的语法如下所示:
{call procedure-name} 
作为实例,在 SQL Server 2005 AdventureWorks 示例数据库中创建以下存储过程:

SQL code
CREATE PROCEDURE GetContactFormalNames AS BEGIN SELECT TOP 10 Title + ' ' + FirstName + ' ' + LastName AS FormalName FROM Person.Contact END


此存储过程返回单个结果集,其中包含一列数据(由 Person.Contact 表中前十个联系人的称呼、名称和姓氏组成)。

在下面的实例中,将向此函数传递 AdventureWorks 示例数据库的打开连接,然后使用 executeQuery 方法调用 GetContactFormalNames 存储过程。
Java code
public static void executeSprocNoParams(Connection con) ...{ try ...{ Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("{call dbo.GetContactFormalNames}"); while (rs.next()) ...{ System.out.println(rs.getString("FormalName")); } rs.close(); stmt.close(); } catch (Exception e) ...{ e.printStackTrace(); } }


2使用带有输入参数的存储过程

使用 JDBC 驱动程序调用带参数的存储过程时,必须结合 SQLServerConnection 类的 prepareCall 方法使用 call SQL 转义序列。带有 IN 参数的 call 转义序列的语法如下所示:
{call procedure-name[([parameter][,[parameter]]...)]} 

构造 call 转义序列时,请使用 ?(问号)字符来指定 IN 参数。此字符充当要传递给该存储过程的参数值的占位符。可以使用 SQLServerPreparedStatement 类的 setter 方法之一为参数指定值。可使用的 setter 方法由 IN 参数的数据类型决定。
向 setter 方法传递值时,不仅需要指定要在参数中使用的实际值,还必须指定参数在存储过程中的序数位置。例如,如果存储过程包含单个 IN 参数,则其序数值为 1。如果存储过程包含两个参数,则第一个序数值为 1,第二个序数值为 2。
作为如何调用包含 IN 参数的存储过程的实例,使用 SQL Server 2005 AdventureWorks 示例数据库中的 uspGetEmployeeManagers 存储过程。此存储过程接受名为 EmployeeID 的单个输入参数(它是一个整数值),然后基于指定的 EmployeeID 返回雇员及其经理的递归列表。下面是调用此存储过程的 Java 代码:

Java code
public static void executeSprocInParams(Connection con) ...{ try ...{ PreparedStatement pstmt = con.prepareStatement("{call dbo.uspGetEmployeeManagers(?)}"); pstmt.setInt(1, 50); ResultSet rs = pstmt.executeQuery(); while (rs.next()) ...{ System.out.println("EMPLOYEE:"); System.out.println(rs.getString("LastName") + ", " + rs.getString("FirstName")); System.out.println("MANAGER:"); System.out.println(rs.getString("ManagerLastName") + ", " + rs.getString("ManagerFirstName")); System.out.println(); } rs.close(); pstmt.close(); } catch (Exception e) ...{ e.printStackTrace(); } }
Publication dates:2009年5月13日 - Writer:技术 部
上一页 | 下一页
Comment
目前还没有评论. 欢迎您第一个发表评论!
点击 此处 以发表评论。
 

重庆中典计算机职业培训学院    2006    版权所有    未经授权禁止复制或建立镜像
咨询电话:023-65353888    咨询QQ:139538889   备案序号:渝ICP备05010489号
地址:重庆市沙坪坝区步行街煌华新纪元2号楼11楼
copyright  ©  2006  Chongqing  Zhongdian  Computer  Institute