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 :
-
方法一:
Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("{call dbo.GetContactFormalNames}"); while (rs.next()) { System.out.println(rs.getString("FormalName")); }
方法二:
CallableStatement callstat = con.prepareCall("{call dbo.GetContactFormalNames}");
ResultSet rs = callstat.executeQuery();
while(rs.next()){
System.out.println(rs.getString(2));
}
2使用带有输入参数的存储过程
使用 JDBC 驱动程序调用带参数的存储过程时,必须结合 SQLServerConnection 类的 prepareCall 方法使用 call SQL 转义序列。带有 IN 参数的 call 转义序列的语法如下所示:
{call procedure-name[([parameter][,[parameter]]...)]}
构造 call 转义序列时,请使用 ?(问号)字符来指定 IN 参数。此字符充当要传递给该存储过程的参数值的占位符。可以使用 SQLServerPreparedStatement 类的 setter 方法之一为参数指定值。可使用的 setter 方法由 IN 参数的数据类型决定。
向 setter 方法传递值时,不仅需要指定要在参数中使用的实际值,还必须指定参数在存储过程中的序数位置。例如,如果存储过程包含单个 IN 参数,则其序数值为 1。如果存储过程包含两个参数,则第一个序数值为 1,第二个序数值为 2。