 |
返回文章
一个简单的 Java 例子
像文中提到的,我们没有时间讨论详细的应用开发。但是如果您希望了解如何使用 Java 应用程序在 DB2 数据库中执行 SQL/XML SELECT 语句,那么您可以查看以下代码。这段代码显示了如何按照给定的邮政编码查找客户的名称。
如果您熟悉 JDBC,那么您将发现这个例子很容易理解。在声明了必要的变量,建立数据库连接之后,我们会创建一个包含 SELECT 语句的字符串。您也许会回忆起来,文章中有另一段 代码 完成类似的操作,只是在这里我们会:
- 使用一个参数表示邮政编码
- 在双引号内使用转义字符书写变量(本例中为 "c" and "x")
- 显式地将输入的参数转换为适当的类型
接下来准备 SELECT 语句,设置 "zipCode" 变量为输入参数。最后,执行语句。
清单 A. 执行 SQL/XML 语句的 Java™ 代码
. . .
// define variables
PreparedStatement selectStmt = null;
String query = null;
ResultSet rs = null;
Connection conn = null;
String zipCode = "95116";
try {
. . .
// get a DB2 database connection following the standard process
. . .
// create the string for our SELECT statement
//
// if we were to issue this query interactively, we'd write:
// select name from clients
// where xmlexists('$c/Client/Address[zip="95116"]'
// passing clients.contactinfo as "c")
//
// because we're including it in a Java program, we need to
// use escape characters around the double quotation marks.
// we also need to explicitly cast our parameter marker value to
// the appropriate type.
query = "select name from clients where xmlexists(" +
"'$c/Client/Address[zip=$x]' "+
"passing clients.contactinfo AS \"c\", cast(? as char(5)) as \"x\" )";
// prepare the statement and set the input parameter
selectStmt = conn.prepareStatement(query);
selectStmt.setString(1, zipCode);
// execute the statement
rs = selectStmt.executeQuery();
// process the results as desired
. . .
// release resources and close the connection
. . .
}
catch (Exception e) { . . . }
|
返回文章
|  |
|