使用 Microsoft JDBC Driver for SQL Server 时,您可能必须处理复杂语句,其中包括运行时动态生成的语句。复杂语句通常执行多种任务,包括更新、插入和删除。这类语句可能还会返回多个结果集和输出参数。在这些情况下,运行该语句的 Java 代码预先可能不知道返回的对象和数据的类型和数目。
为了有效地处理复杂语句,JDBC 驱动程序提供多种方法查询返回的对象和数据,以便您的应用程序可正确处理这些内容。处理复杂语句的关键在于 SQLServerStatement 类的 execute 方法。此方法将返回 boolean 值。当该值为 true 时,从该语句返回的第一个结果为结果集。当该值为 false 时,返回的第一个结果为更新计数。
知道返回的对象或数据的类型后,可以使用 getResultSet 或 getUpdateCount 方法处理这些数据。要继续处理从复杂语句返回的下一个对象或数据,可以调用 getMoreResults 方法。
在下面的实例中,将向此函数传递 SQL Server 2005 AdventureWorks 示例数据库的打开连接,构造一条组合了存储过程调用和 SQL 语句的复杂语句,再运行这些语句,然后使用 do 循环处理返回的所有结果集和更新计数。
public static void executeComplexStatement(Connection con) {
try {
String sqlStringWithUnknownResults = "{call dbo.uspGetEmployeeManagers(50)};SELECT TOP 10 * FROM Person.Contact";
Statement stmt = con.createStatement();
boolean results = stmt.execute(sqlStringWithUnknownResults);
int count = 0;
do {
if (results) {
ResultSet rs = stmt.getResultSet();
System.out.println("Result set data displayed here.");
rs.close();
} else {
count = stmt.getUpdateCount();
if (count >= 0) {
System.out.println("DDL or update data displayed here.");
} else {
System.out.println("No more results to process.");
}
}
results = stmt.getMoreResults();
} while (results || count != -1);
stmt.close();
}
catch (Exception e) {
e.printStackTrace();
}
}