 |
返回文章
一个简单的 Java 例子
如文章中所述,我们在这里没有时间详细讨论应用程序开发方面的话题。但是您也许想知道如何在 Java 应用程序中嵌入 XQuery,为了满足您这个要求,我们在下面给出了一个代码摘录。这个摘录展示了如何检索居住在具有给定邮政编码的地区的客户的地址。
XQuery 不支持参数占位符,所以将 XQuery 嵌入在 Java 应用程序中时,需要将 XQuery 封装(或嵌入)在 SQL 语句中。“用 SQL 查询 DB2 XML 数据” 讨论了 SQL/XML 的 XMLQuery 函数,我们在这个例子中使用了该函数。
如果您熟悉 JDBC,那么应该发现这个例子中大部分内容比较容易理解。该代码在声明和定义了必要的变量后,按照标准的 DB2 方法建立一个数据库连接。接着,创建一个包含查询语句的字符串。在这个例子中,我们实际上定义了两个不同但是等价的查询字符串:query1 和 query2。query1 使用 FLWOR 表达式,以便与前面的例子相对应。query2 则使用一个更简单的路径表达式,但是其效果是等价的。
逻辑上,这个例子中的代码等价于之前的例子(清单 10. 带有新的 “where” 子句的 FLWOR 表达式 ),不同的是它:
-
将 XQuery 嵌入在一个 SQL
SELECT 语句中。在 XQuery 被嵌入在 SQL 语句中时,它不再需要调用 db2-fn:xmlcolumn 或 db2-fn:sqlquery 来获得输入数据。相反,XQuery 通过由 PASSING 子句从 SQL 传递给它的变量来获得输入数据。
-
为邮政编码值使用参数占位符。
-
在查询字符串中需要使用双引号的地方使用换码符(反斜杠)。在这个例子中,
PASSING 子句使用了换码符将变量 “t”、“y” 和 “z” 括起来。
-
显式地将输入参数的值覆盖为适当的数据类型。
然后准备好 SELECT 语句,将它的输入参数设置为目标值,这个值是在 Java “zipCode” 变量中定义的。我们在这里使用了 String 类型,因为 “DB2 Viper 快速入门” 中创建的 XML 模式将邮政编码定义为 XML 字符串。最后,执行语句,按要求处理返回的结果,并关闭数据库连接。
发出 XQuery 的 Java 应用程序代码摘录
. . .
// define variables
String zipCode = "95116";
PreparedStatement selectStmt = null;
String output = null;
ResultSet rs = null;
try {
. . .
// get a DB2 database connection following the standard process
. . .
// create the string for our query.
// we must embed our XQuery in SQL so we can pass in a parameter.
// furthermore, we must use escape characters around double quotes.
//
// this query uses a FLWOR expression to
// obtain addresses of customers who live in a specific zip code.
String query1 = "select xmlquery("+
" 'for $t in $y/Client/Address where $y/zip=$z" +
"return $t' passing contactinfo as \"y\", " +
"cast (? as varchar(5)) as \"z\") " +
"from clients";
// this equivalent query uses a path expression for the same purpose.
String query2 = "select xmlquery("+
" '$y/Client/Address[zip=$z]' " +
" passing contactinfo as \"y\", " +
"cast (? as varchar(5)) as \"z\") " +
"from clients";
// prepare the statement and set the input parameter.
// since the two previous query strings are equivalent,
// we can use either one.
// we're using the shorter version (query2) here.
selectStmt = conn.prepareStatement(query2);
selectStmt.setString(1, zipCode);
// execute the statement
rs = selectStmt.executeQuery();
// process the results as desired
. . .
// release resources and close the connection
. . .
}
catch (Exception e) { . . . }
|
返回文章
|  |
|