8 Using the jXTransformer API
In a JDBC programming environment, you use the jXTransformer API to perform the following tasks:
- Execute jXTransformer write statements (Insert, Update, or Delete) to write data to a relational database from an XML document and return a n update count of the rows inserted, updated, or deleted.
This chapter describes the jXTransformer API and the classes it uses to process jXTransformer queries and write statements. It also provides information about connecting to the database and about using jXTransformer queries and write statements in a Java application.
See Chapter 7 "Using the SQL/XML JDBC Driver and JDBC API Extensions" for information about the JDBC API extension classes and methods used to execute SQL/XML queries, about connecting to the database, and about using SQL/XML queries in a Java application.
jXTransformer API Classes
Table 8-1 lists and defines the jXTransformer API classes in the com.ddtek.jxtr package that can be used to create and execute jXTransformer queries and jXTransformer write statements.
Table 8-1. jXTransformer API Classes Class Description com.ddtek.jxtr.JXTRColInfo Implements methods that allow you to work with XML that is returned from a jXTransformer query as a result set. com.ddtek.jxtr.JXTRException Implements a Java exception object that is thrown if an unexpected occurrence is encountered during the processing of a jXTransformer method. com.ddtek.jxtr.JXTRQuery Implements the methods required to:
- Transform the XML results from a jXTransformer query into a result set
- Generate a DTD or schema based on the jXTransformer query that describes the XML structure
- Add document-level processing instructions and comments
- Add a reference to a public or private external DTD or an externally stored XML schema
See "JXTRQuery and JXTRResultSetWrapper Classes" for more information. com.ddtek.jxtr.JXTRResultSetWrapper Implements the methods required to execute a SQL query and generate an element-centric or attribute-centric XML document. This class wraps XML elements or attributes around the row and column data that is retrieved from the database. Use this class when you do not want to define the hierarchical structure of an XML document.See "JXTRQuery and JXTRResultSetWrapper Classes" for more information. com.ddtek.jxtr.JXTRSaxInputSource Implements the methods that extend the SAX2 InputSource interface and is typically used with a JXTRSaxReader object. com.ddtek.jxtr.JXTRSaxReader Implements the methods required to implement a SAX2 XMLReader interface and is used with a JXTRResultSetWrapper or JXTRQuery object. com.ddtek.jxtr.JXTRSingleTableUpdate Implements the methods required to execute a SQL Insert, Update, or Delete statement based on one or multiple sets of parameter marker values retrieved from an input XML document.See "JXTRUpdate and JXTRSingleTableUpdate Classes" for more information. com.ddtek.jxtr.JXTRSingleTableUpdateException Implements a Java exception object that is thrown if an unexpected occurrence is encountered during the processing of a SQL Insert, Update, or Delete statement. com.ddtek.jxtr.JXTRStatement Implements the methods required to determine if a jXTransformer statement is a jXTransformer query statement or a jXTransformer Insert, Update, or Delete statement. com.ddtek.jxtr.JXTRUpdate Implements the methods required to:
- Specify the format of the XML document from which the data will be retrieved
- Specify values for parameter markers
See "JXTRUpdate and JXTRSingleTableUpdate Classes" for more information. com.ddtek.jxtr.JXTRUpdateException Implements a Java exception object that is thrown if an unexpected occurrence is encountered during the processing of a jXTransformer Insert, Update, or Delete statement. com.ddtek.jxtr.JXTRWarning Extends JXTRException and implements a Java throwable object that is created if a warning condition is encountered during the processing of a jXTransformer method. The object that is thrown can reference other exceptions.JXTRQuery and JXTRResultSetWrapper Classes
Table 8-2 lists some common tasks that you can perform using the methods of the JXTRQuery and JXTRResultSetWrapper classes. These two classes are the most frequently used jXTransformer API classes when you are working with jXTransformer queries.
For more information about each jXTransformer API class in the com.ddtek.jxtr package, see the Javadoc shipped with Connect for SQL/XML.
JXTRUpdate and JXTRSingleTableUpdate Classes
Table 8-3 lists some common tasks that you can perform using the methods of the JXTRUpdate and JXTRSingleTableUpdate classes. These classes are the most frequently used jXTransformer API classes when you are working with jXTransformer write statements.
JXTRUpdate Class
For more information about each jXTransformer API class in the com.ddtek.jxtr package, see the Javadoc shipped with Connect for SQL/XML.
JXTRSingleTableUpdate Class
The JXTRSingleTableUpdate class performs the tasks described in Table 8-4.
For more information about each jXTransformer API class in the com.ddtek.jxtr package, see the Javadoc shipped with Connect for SQL/XML.
Connecting to the Database
Once Connect for SQL/XML is installed and your application is using the jXTransformer API, you can connect from your application to your database in either of the following ways:
- Using a JNDI data source. For information about using JNDI data sources to connect, refer to either the DataDirect Connect for JDBC User's Guide and Reference or the DataDirect SequeLink Developer's Reference, depending on the DataDirect Technologies JDBC driver you are using.
You can connect through the JDBC Driver Manager with the DriverManager.getConnection method. This method takes one parameter, a string that contains a URL.
The following list provides a summary of the steps you take to connect to the database. After this list, each step is described in more detail.
- Register the driver.
- Pass the driver's connection URL.
- Test the connection.
1. Setting the Classpath
The jar files that must be defined in your CLASSPATH variable depend on whether you are using a Connect for JDBC driver or the SequeLink for JDBC driver. If the files are not defined on your CLASSPATH, you will receive the
class not founderror when trying to load the driver.DataDirect Connect for JDBC Drivers
Set your system CLASSPATH to include the following entries, where
driver.jaris the driver jar file (for example, sqlserver.jar) andinstall_diris the path to your Connect for SQL/XML installation directory:install_dir/lib/base.jarinstall_dir/lib/util.jarinstall_dir/lib/jxtr.jarinstall_dir/lib/driver.jarWindows Example
CLASSPATH= .;c:\CfSQLXML\lib\base.jar;c:\CfSQLXML\lib\util.jar; c:\CfSQLXML\lib\jxtr.jar;c:\CfSQLXML\lib\sqlserver.jarUNIX Example
CLASSPATH=.;/home/user1/CfSQLXML/lib/base.jar;/home/user1/ CfSQLXML/lib/util.jar;/home/user1/CfSQLXML/lib/jxtr.jar;/ho me/user1/CfSQLXML/lib/sqlserver.jarDataDirect SequeLink JDBC Driver
Set your system CLASSPATH to include the following entries where
install_diris the path to your Connect for SQL/XML installation directory:Windows Example
UNIX Example
2. Registering the Driver
Registering the driver tells the JDBC Driver Manager which driver to load. One way to register a DataDirect Technologies JDBC driver is to explicitly load the driver class using the standard Class.forName() method and call DriverManager.getConnection().
DataDirect Connect for JDBC Drivers
See the following list for the class names of each Connect for JDBC driver:
- com.ddtek.jdbc.informix.InformixDriver
- com.ddtek.jdbc.oracle.OracleDriver
- com.ddtek.jdbc.sqlserver.SQLServerDriver
- com.ddtek.jdbc.sybase.SybaseDriver
For example:
DataDirect SequeLink JDBC Driver
The class name of the SequeLink JDBC Driver is com.ddtek.jdbc.sequelink.SequeLinkDriver.
For example:
For information about alternative methods of registering the SequeLink JDBC Driver, refer to the DataDirect SequeLink Developer's Reference.
3. Passing the Connection URL
After registering the driver, you can pass your database connection information in the form of a connection URL.
DataDirect Connect for JDBC Drivers
See the following URL formats for each Connect for JDBC driver. Use them as templates to create your own connection URLs, substituting the appropriate values specific to your database.
DB2 UDB1
DB2 OS/390 and iSeries1
jdbc:datadirect:db2://server_name:50000;Location=db2_location; CollectionId=your_collectionname;PackageName=your_packagenameInformix
jdbc:datadirect:informix://server_name:2003;InformixServer=your_server; DatabaseName=your_databaseOracle
SQL Server 2
Sybase
1Refer to the DB2 driver chapter of the DataDirect Connect for JDBC User's Guide and Reference before configuring your initial connection.2For instructions on connecting to named instances, refer to the SQL Server driver chapter of the DataDirect Connect for JDBC User's Guide and Reference.For example, to specify a connection URL for SQL Server that includes the user ID and password:
Connection conn = DriverManager.getConnection ("jdbc:datadirect:sqlserver://server1:1433;User=test;Password=secret");NOTES:
- The numeric value after the server name is the port number on which the database is listening. The values listed here are sample defaults. You should determine the port number that your database is using and substitute that value.
Refer to the DataDirect Connect for JDBC User's Guide and Reference for a list of connection properties for each driver.
DataDirect SequeLink for JDBC Driver
The connection URL format is:
NOTES:
portis the TCP/IP port on which the SequeLink server is listening. A default installation of SequeLink Server uses the port 19996.
key=valuespecifies connection properties. Refer to the DataDirect SequeLink Developer's Reference for a list of valid connection properties for the SequeLink JDBC driver.The following examples show some typical SequeLink JDBC driver connection URLs:
jdbc:sequelink://sequelinkhost:19996; jdbc:sequelink://189.23.5.25:19996;user=john; password=whatever jdbc:sequelink://189.23.5.132:19996;databaseName=stores7 jdbc:sequelink://189.23.5.68:19996;databaseName=pubs; HUser=john;HPassword=whatever jdbc:sequelink://sequelinkhost:4006;databaseName=pubs; DBUser=john;DBPassword=whatever4. Testing the Connection
To test your connection to the database, you can use the DataDirect Query Builder for SQL/XML, a tool provided with Connect for SQL/XML for creating and modifying Connect for SQL/XML queries. You can create your own Connect for SQL/XML query for testing or use one of the example Connect for SQL/XML queries in the examples/src/examples/jxtrapi directory in the Connect for SQL/XML installation directory. See "Connecting to the Database" for instructions on using the DataDirect Query Builder for SQL/XML to connect to the database.
Using jXTransformer Queries and Write Statements in a Java Application
NOTE: To compile and run Java applications that use jXTransformer queries and write statements, you must add the appropriate jar files to your classpath. For information about the jar files you need to add, refer to the DataDirect Connect for SQL/XML Installation Guide.
Typically, a Java application containing a jXTransformer query or write statement performs the following tasks:
- Prepares the jXTransformer query or write statement in a String object.
- Creates a JXTRQuery or JXTRUpdate object, passing in the JDBC connection and the jXTransformer query or write statement.
- Sets options that are available to the jXTransformer query or write statement.
- Optionally, sets parameters for the query or write statement.
- Uses one of the execute methods to execute the query or write statement. In the case of a jXTransformer query, the method used to execute the jXTransformer query determines the format of the resulting XML (DOM, JDOM, SAX2 event stream, or Writer) or result set. In the case of a jXTransformer write statement, the method also returns an update count of rows inserted, updated, or deleted.
The following examples show a jXTransformer query and a jXTransformer write statement in a Java application.
Example A: jXTransformer Query
The following example shows a jXTransformer query in a Java application. For more examples of jXTransformer queries that demonstrate specific features and functions in a Java application, refer to the examples_readme.txt file in the examples directory in your Connect for SQL/XML installation directory.
/* *--------------------------------------------------------------------------- * Copyright(c) 2003 DataDirect Technologies. All rights reserved. * * This product includes Xerces, developed by the Apache Software * Foundation (http://www.apache.org). Copyright (C) 1999-2000 The Apache * Software Foundation. All rights reserved. * * This product includes Xalan, developed by the Apache Software * Foundation (http://www.apache.org). Copyright (C) 1999-2000 The Apache * Software Foundation. All rights reserved. * * This product includes JDOM, developed by the JDOM Project * (http://jdom.org). Copyright (C) 2001 Brett McLaughlin & Jason Hunter. * All rights reserved. * * Description: * * JXTRExample1: * Demonstrates * (a) Basic XML document fragment construction features. * (b) Writing the XML result to a writer created from System.out. * * The example can be invoked either through the Example class or by invoking * the main in this class. * * See the accompanying readme file for more information on the * provided examples. * * -------------------------------------------------------------------------- */ package examples.jxtrapi; import java.io.OutputStreamWriter; import java.sql.*; import com.ddtek.jxtr.*; import examples.*; public class JXTRExample1 extends Example { /** * Executes the 'JXTRExample1' example */ public void execute() throws Exception { // Output example description System.out.println( "==============================" ); System.out.println( "= JXTR Example1 demonstrates =" ); System.out.println( "==============================" ); System.out.println( " (a) Basic XML document fragment construction." ); System.out.println( " (b) Writing the XML to a writer created from System.out." ); // Load properties from the resource loadProperties(); // Create JDBC connection connectWithStandardJDBC(); // Build JXTR query StringBuffer jxtrQ = new StringBuffer(); jxtrQ.append ( "select " ); jxtrQ.append ( " xml_element ('employee', " ); jxtrQ.append ( " xml_attribute('ID', e.EmpId), " ); jxtrQ.append ( " xml_element('names', " ); jxtrQ.append ( " xml_element('first', e.FirstName), " ); jxtrQ.append ( " xml_element('last', e.LastName)), " ); jxtrQ.append ( " xml_element('hire-dates', " ); jxtrQ.append ( " xml_attribute('start', e.StartDate), " ); jxtrQ.append ( " xml_attribute('end', e.EndDate)), " ); jxtrQ.append ( " xml_cdata(e.Resume)) " ); jxtrQ.append ( "from Employees e where e.EmpId in (12, 14) " ); // Construct new JXTRQuery object JXTRQuery jxtrQuery = new JXTRQuery ( conn, new String ( jxtrQ ) ); // Output result header System.out.println( "------------------------------------" ); System.out.println( "Query result (without implicit root)" ); System.out.println( "------------------------------------" ); // Execute OutputStreamWriter systemOutWriter = new OutputStreamWriter ( System.out ); boolean generateImplicitRoot=false; jxtrQuery.executeWriter ( systemOutWriter, generateImplicitRoot, systemOutWriter.getEncoding (), 2 ); // Output result header System.out.println( "---------------------------------" ); System.out.println( "Query result (with implicit root)" ); System.out.println( "---------------------------------" ); // Execute generateImplicitRoot=true; jxtrQuery.executeWriter ( systemOutWriter, generateImplicitRoot, systemOutWriter.getEncoding (), 2 ); // Close JDBC connection disconnect(); } /** * Main method. */ public static void main ( String[] args ) throws Exception { Example thisDemo = new JXTRExample1(); thisDemo.execute(); } }Example B: jXTransformer Write Statement
The following example shows a jXTransformer write statement in a Java application. For more examples of jXTransformer write statements that demonstrate specific features and functions in a Java application, refer to the examples_readme.txt file in the examples directory in your Connect for SQL/XML installation directory.
/* *--------------------------------------------------------------------------- * Copyright(c) 2003 DataDirect Technologies. All rights reserved. * * This product includes Xerces, developed by the Apache Software * Foundation (http://www.apache.org). Copyright (C) 1999-2003 The Apache * Software Foundation. All rights reserved. * * This product includes Xalan, developed by the Apache Software * Foundation (http://www.apache.org). Copyright (C) 1999-2003 The Apache * Software Foundation. All rights reserved. * * This product includes JDOM, developed by the JDOM Project * (http://jdom.org). Copyright (C) 2003 Brett McLaughlin & Jason Hunter. * All rights reserved. * * Description: * * JXTRExample9: * Demonstrates * (a) Basic insert from an XML document into multiple database tables. * (b) Writing the number of inserted rows to System.out. * * The example can be invoked either through the Example class or by invoking * the main in this class. * * See the accompanying readme file for more information on the * provided examples. * *--------------------------------------------------------------------------- */ package examples.jxtrapi; import java.io.OutputStreamWriter; import java.sql.*; import com.ddtek.jxtr.*; import examples.*; public class JXTRExample9 extends Example { /** * Executes the 'JXTRExample9' example */ public void execute() throws Exception { // Output example description System.out.println( "==============================" ); System.out.println( "= JXTR Example9 demonstrates =" ); System.out.println( "==============================" ); System.out.println( " (a) Basic insert from an XML document into multiple database tables." ); System.out.println( " (b) Writing the number of inserted rows to System.out." ); // Load properties from the resource loadProperties(); // Create JDBC connection connectWithStandardJDBC(); // Turn off autocommit conn.setAutoCommit ( false ); // Set table names String[] table = new String[] {"Employees", "EmpBenefits", "Assignments"}; // Build JXTR query StringBuffer jxtrU = new StringBuffer(); jxtrU.append ( "insert xml_document('data/Insert.xml', 1) " ); jxtrU.append ( " into " + table[0] + "(EmpId, FirstName, LastName, Title, StartDate, HourlyRate, Resume) " ); jxtrU.append ( " xml_row_pattern('/root/employee') " ); jxtrU.append ( " values( xml_xpath('@ID', 'Integer'), " ); jxtrU.append ( " xml_xpath('@FirstName'), " ); jxtrU.append ( " xml_xpath('@LastName'), " ); jxtrU.append ( " xml_xpath('@Title'), " ); if ( dateOrTimestamp == java.sql.Types.DATE ) jxtrU.append ( " xml_xpath('@StartDate', 'Date'), " ); else jxtrU.append ( " xml_xpath('@StartDate', 'Timestamp'), " ); jxtrU.append ( " xml_xpath('@HourlyRate', 'Integer'), " ); jxtrU.append ( " xml_xpath('resume[1]/text()') " ); jxtrU.append ( " ) " ); jxtrU.append ( " into " + table[1] + "(BenefitId, EmpId, Amount, StartDate) " ); jxtrU.append ( " xml_row_pattern('/root/employee/benefits/benefit') " ); jxtrU.append ( " values( xml_xpath('@ID', 'Integer'), " ); jxtrU.append ( " xml_xpath('../../@ID', 'Integer'), " ); jxtrU.append ( " xml_xpath('@Amount', 'Integer'), " ); if ( dateOrTimestamp == java.sql.Types.DATE ) jxtrU.append ( " xml_xpath('@StartDate', 'Date') " ); else jxtrU.append ( " xml_xpath('@StartDate', 'Timestamp') " ); jxtrU.append ( " ) " ); jxtrU.append ( " into " + table[2] + "(ProjId, EmpId, Task) " ); jxtrU.append ( " xml_row_pattern('/root/employee/projects/project/task') " ); jxtrU.append ( " values(xml_xpath('../@ID', 'Integer'), " ); jxtrU.append ( " xml_xpath('../../../@ID', 'Integer'), " ); jxtrU.append ( " xml_xpath('text()') " ); jxtrU.append ( " ) " ); // Construct new JXTRUpdate object JXTRUpdate jxtrUpdate = new JXTRUpdate ( conn, new String ( jxtrU ) ); // XML document contains ISO8601 timestamps. jxtrUpdate.setTimestampEncoding(JXTRUpdate.TIMESTAMP_AS_ISO8601); // Execute int[][] insertCount = null; try { insertCount = jxtrUpdate.executeUpdate(); } catch ( Exception ex ) { System.out.println ( "!!! Insert failed !!!" ); if ( ex instanceof JXTRUpdateException ) { // Get failed count. insertCount = ((JXTRUpdateException)ex).getUpdateCount(); } // Rollback changes conn.rollback(); // Throw again. throw ex; } finally { // Write change count to System.out if ( insertCount == null ) { System.out.println( "--------------------------" ); System.out.println( "No insert count available." ); System.out.println( "--------------------------" ); } else { // Output count header System.out.println( "------------" ); System.out.println( "Insert count" ); System.out.println( "------------" ); // Write total change count per table to System.out. for ( int i = 0; i < insertCount.length; i++ ) { int count = 0; for ( int j = 0; j < insertCount[i].length; j++ ) { count += insertCount[i][j]; } System.out.println ( count + " row(s) were inserted into table " + table[i] ); } } } // Commit changes conn.commit(); // Close JDBC connection disconnect(); } /** * Main method. */ public static void main ( String[] args ) throws Exception { Example thisDemo = new JXTRExample9(); thisDemo.execute(); } }
![]()