 |
返回文章
一个简单的 Java 例子
像文中提到的,我们没有时间讨论详细的应用开发。但是如果您希望了解如何使用 Java 应用程序向 DB2 中插入 XML 数据,那么您可以查看以下代码。这段代码显示了如何将一条对应“John Smith”的数据插入到“clients”表中。您也许会回忆起来,文章中曾经说明了如何使用交互的手段 完成同样的操作。
如果您熟悉 JDBC,那么您将发现这个例子很容易理解。在声明了必要的变量,建立数据库连接之后,我们会准备一个 INSERT 语句。如果您仔细查看语句(在 "sqls" 变量中定义)中包含的字符串,您将发现它和您写的其他 INSERT 语句其实十分相似。
您还可以更改其中的参数。前三个参数很容易理解——它们用来设置整数和字符串列中的数据。第 4 个参数用来把数据插入到 XML 列 ("contactinfo")。在这里,您将创建一个 FileInputStream 流对象,将 XML 文件的文件名和长度传递进去,再将这个流对象传递给语句对象的 setBinaryStream() 方法,这样就设置了将要插入到 "contactinfo" 列中的 XML 数据的值。
列表 1. 将 XML 数据从文件插入 DB2 XML 列的 Java 代码
. . .
// connection variable
Connection conn = null;
// input variables
int id = 77;
String name = "John Smith";
String status = "Gold";
String fn = "Client77.xml"; // this is our XML file
// SQL INSERT string
// we'll be inserting XML and non-XML data into the clients table
String sqls =
"insert into clients (id, name, status, contactinfo) values (?, ?, ? ,?)";
// Here's a slight variation of the above INSERT string,
// which we'd use if we wanted to validate the XML document against a schema
String sqlv = "INSERT INTO clients (id, name, status, contactinfo) " +
"VALUES (?, ?, ?, xmlvalidate(? according to xmlschema id user1.mysample))";
// get a database connection
// following standard DB2 procedure
. . .
// prepare and execute the INSERT statement
PreparedStatement insertStmt = conn.prepareStatement(sqls);
insertStmt.setInt(1, id);
insertStmt.setString(2, name);
insertStmt.setString(3, status);
File file = new File(fn);
insertStmt.setBinaryStream(4, new FileInputStream(file), (int)file.length());
if (insertStmt.executeUpdate() != 1) {
System.out.println("insertBinStream:: No record inserted.");
. . .
}
else { . . . }
. . .
// close the connection following the standard DB2 process
. . .
|
这个示例同样能帮助您理解如何在 INSERT 操作中验证 XML 数据。请查看 "sqlv" 变量,这个 SQL 字符串看起来像一个标准的 INSERT 语句,只是它在 VALUES 子句的第 4 个参数处调用了一个 XMLVALIDATE 函数。如果您执行了这条语句,DB2 会尝试按照 user1.mysample 模式来验证 XML 文档。如果 DB2 检测到输入的文档不符合 XML 模式,会返回一条错误,同时没有数据插入到数据库中。
返回文章
|  |
|