|
|||||||||
|
The Sample Program
Because JDBC 4 was officially released on December 11, 2006, very few databases offer drivers for it yet and none offer full support at this time. This example uses the latest Apache Derby version, 10.2, to introduce you to storing and querying XML data (see Listing 1. Sample Program Storing and Querying XML). Derby, however, does not yet support java.sql.SQLXML, which means that you cannot directly bind into or retrieve XML values from a result set. This may seem like a major shortcoming considering the purpose of this article, but since Derby is SQL 2003-compliant and can easily be used in the embedded mode, it still works for demonstrating how XML data retrieval would happen if you had a fully compliant driver available.
Derby's XML operators, such as XMLPARSE and XMLSERIALIZE, help you convert data to character streams or strings for use in your program. Following each sample task in this example, I will also show how the task would be accomplished with a fully SQL/XML-compliant driver. In fact, you could substitute each task in the sample code with example snippets that use java.sql.SQLXML and the code still will successfully compile. However, running the program would result in a Derby-specific error, such as "Binding directly to an XML value is not allowed." In short, the sample code primarily shows how to interact with an SQL/XML-compliant database. I will separately list a code snippet for each task that uses java.sql.SQLXML to do the same as the sample program. First, create a simple table that includes an XML data type:
Insert XML Data
Now, if you had a fully JDBC 4-compliant driver, you could accomplish the same by using java.io.Writer (remember, you can still compile the code with this change):
Or by using javax.xml.transform.dom.DOMSource:
Retrieve XML Data
With support for java.sql.SQLXML, you can accomplish the same task by simply selecting the column with the XML database type. You would get the XML data directly. Suppose you would like to use the DOM parser to evaluate the XML retrieved from the result set:
Instead of calling getBinaryStream(), you could have called getSource(Class
XPath with XMLEXISTS
Note that you can also use the XMLQUERY function to execute any XQuery expressions. However, since both the XMLEXISTS predicate and XMLQUERY function are more SQL 2003 features than JDBC 4 features, this article doesn't cover these features further.
Endless Possibilities
The sqlxml variable of course is an instance of java.sql.SQLXML that you retrieved from the database. No conversions are required. In essence, you have been able to transform your XML content stored in the database into XHTMLin only five lines.
|
|||||||||
Oliver Kaljuvee is a consultant developing software for companies in the financial industry in New York City.
| |||||||||
|