Preparing XQuery Statements
Typically, when a query is executed, the query is parsed and optimized before it is run. To avoid incurring this overhead each time the query is used, you can prepare the same query once and execute it multiple times.
The following is the code for creating a prepared query. Only the last line differs from the code used to create a query in our example in Querying Data from XML Files or DOM Trees.
DDXQDataSource ds = new DDXQDataSource(); XQConnection conn = ds.getConnection(); FileReader fileReader = new FileReader("flwor.xq"); XQPreparedExpression preparedExpression = conn.prepareExpression(fileReader);Once the query is prepared, use an executeQuery() call to execute it.
XQSequence xqSequence = preparedExpression.executeQuery(); System.out.println(xqSequence.getSequenceAsString(null));Queries can accept parameters that can be changed between executions. For example, you may want to prepare a query that selects holdings based on a particular customer. In the following query, the value of userid changes each time this XQuery is run. (Each userid is associated with a specific customer.)
The value of $l is set using XQJ. Let's run this twice, each time for different users.
preparedExpression.bindString(new QName("l"), "Jonathan"); xqSequence xqSequence = preparedExpression.executeQuery(); System.out.println("\n\nHoldings for Jonathan:\n\n"); System.out.println(xqSequence.getSequenceAsString(null)); preparedExpression.bindString(new QName("l"), "Minollo"); xqSequence xqSequence = preparedExpression.executeQuery(); System.out.println("\n\nHoldings for Minollo:\n\n"); System.out.println(xqSequence.getSequenceAsString(null));Other similar examples can be found in the ResultRetrieval example.