FWIW, after making the changes mentioned earlier so it would work better with MySQL, I've also modified it so it uses XMLStreamWriter, allowing it to process larger files. Here's the updated Dbsql2xml.java file containing the changes for both MySQL and XMLStreamWriter:
*The"dbsql2xml"isJavatool(class)fortransforming(export)relationaldatabasesintohierarchicalXML.Copyright(C)*2005�2006StepanRybarThislibraryisfreesoftware;youcanredistributeitand/ormodifyitunderthetermsoftheGNU*LesserGeneralPublicLicenseaspublishedbytheFreeSoftwareFoundation;eitherversion2.1oftheLicense,or(atyour*option)anylaterversion.Thislibraryisdistributedinthehopethatitwillbeuseful,butWITHOUTANYWARRANTY;without*eventheimpliedwarrantyofMERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNULesserGeneralPublicLicense*formoredetails.YoushouldhavereceivedacopyoftheGNULesserGeneralPublicLicensealongwiththislibrary;ifnot,*writetotheFreeSoftwareFoundation,Inc.,59TemplePlace,Suite330,Boston,MA02111-1307USAFormoreinformation,see*http://sourceforge.net/projects/dbsql2xml/StepanRYBARModra6Stodulky1979PrahatheCzechRepublicxrybs01@seznam.cz*http://sourceforge.net/projects/dbsql2xml/*/packagenet.sf.dbsql2xml;importjava.io.ByteArrayOutputStream;importjava.io.File;importjava.io.OutputStream;importjava.io.FileOutputStream;importjava.io.ByteArrayOutputStream;importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.PreparedStatement;importjava.sql.ResultSet;importjava.sql.ResultSetMetaData;importjava.sql.Statement;importjava.text.SimpleDateFormat;importjava.util.ArrayList;importjava.util.Date;importjava.util.HashMap;importjava.util.Iterator;importjava.util.Set;importjava.util.Vector;importjavax.xml.parsers.DocumentBuilder;importjavax.xml.parsers.DocumentBuilderFactory;importjavax.xml.stream.XMLOutputFactory;importjavax.xml.stream.XMLStreamWriter;importorg.apache.commons.logging.Log;importorg.apache.commons.logging.LogFactory;importorg.w3c.dom.Document;importorg.w3c.dom.Element;importorg.w3c.dom.Node;importorg.w3c.dom.NodeList;importorg.w3c.dom.ProcessingInstruction;importorg.w3c.dom.Text;/** * <code>dbsql2xml</code> <br /> * "dbsql2xml" is Java tool (class) for transformation (export, convert) * relational database into hierarchical XML. It requires JRE 5.0, JDBC and SQL * DBMS. "dbsql2xml" uses XML document for mapping database tables and columns * into elements of tree XML. <br /> * For more information see "https://sourceforge.net/projects/dbsql2xml/". * * @version 0.21 2006-01-08 - modified by Dallan Quass 2010-02-02 */publicclassDbsql2xml{privateLog log =LogFactory.getLog(Dbsql2xml.class);privateboolean connnectionPassed =true;privateString applicationInfo =null;privateString pathToMappingXmlFile =null;privateString pathToXsdFile =null;privateString namesOfGlobalVariables =null;privateString valuesOfGlobalVariables=null;privateString pathToOutputXmlFile =null;privateString globalCharsetName =null;privateHashMap globalVariables =newHashMap();privateConnection connection =null;privateStatement globalStatement =null;privateXPathHelper xPathHelper =newXPathHelper();privateXMLStreamWriter writer =null;privateboolean multiStatementDriver =true;privatelong totalTime =0;privatelong xmlTime =0;privateString jdbcDriver =null;privateString jdbcURL =null;privateString jdbcUserName =null;privateString jdbcPassword =null;privateString connUrl =null;/** * Creates a <code>dbsql2xml</code> for output to <code>File</code>. * * @param pathToMappingXmlFile * e.g "treeXMLMapping.xml" * @param pathToXsdFile * e.g. "dbsql2xml.xsd" * @param namesOfGlobalVariables * e.g. "$gvG01#$gvG02#$gvG03" or "myVarX#myVarY#myVarZ" * @param valuesOfGlobalVariables * e.f "01#John Smith#2005-05-10" * @param pathToOutputXmlFile * e.g "treeXMLOut.xml" <br /> * <br /> * token, which delimites names and values of global variables, is * set in mapping XML file inside element * <code>tokenForCommandLineStringArrays</code> <br /> * it can be single or multiple character <br /> * token is the same for names and values of global variables <br /> * <br /> * So example of creating <code>dbsql2xml</code> object is: <br /> * <code>dbsql2xml myDbSql2Xml = new dbsql2xml("treeXMLMapping.xml", "dbsql2xml.xsd", "$gvG01", "001", "treeXMLOut.xml");</code> * <br /> * See example in distribution (standalone application and servlet). */publicDbsql2xml(StringpathToMappingXmlFile,StringpathToXsdFile,StringnamesOfGlobalVariables,StringvaluesOfGlobalVariables,StringpathToOutputXmlFile){this.pathToMappingXmlFile=pathToMappingXmlFile;this.pathToXsdFile=pathToXsdFile;this.namesOfGlobalVariables=namesOfGlobalVariables;this.valuesOfGlobalVariables=valuesOfGlobalVariables;this.pathToOutputXmlFile=pathToOutputXmlFile;this.connection=null;this.connnectionPassed=false;log.debug("CreatingDbsql2xmlwith:" + "\npathToMappingXmlFile=" + pathToMappingXmlFile + "\npathToXsdFile=" + pathToXsdFile + "\nnamesOfGlobalVariables=" + namesOfGlobalVariables + "\nvaluesOfGlobalVariables=" + valuesOfGlobalVariables + "\npathToOutputXmlFile=" + pathToOutputXmlFile); } public Dbsql2xml(String pathToMappingXmlFile, String pathToXsdFile, String namesOfGlobalVariables, String valuesOfGlobalVariables, String pathToOutputXmlFile, Connection con) { this.pathToMappingXmlFile = pathToMappingXmlFile; this.pathToXsdFile = pathToXsdFile; this.namesOfGlobalVariables = namesOfGlobalVariables; this.valuesOfGlobalVariables = valuesOfGlobalVariables; this.pathToOutputXmlFile = pathToOutputXmlFile; this.connection = con; log.debug("CreatingDbsql2xmlwith:" + "\npathToMappingXmlFile=" + pathToMappingXmlFile + "\npathToXsdFile=" + pathToXsdFile + "\nnamesOfGlobalVariables=" + namesOfGlobalVariables + "\nvaluesOfGlobalVariables=" + valuesOfGlobalVariables + "\npathToOutputXmlFile=" + pathToOutputXmlFile); } /** * Creates a <code>dbsql2xml</code> for output to <code>String</code>, * <code>Document</code> and <code>System.out</code>. * * @param pathToMappingXmlFile * e.g "treeXMLMapping.xml" * @param pathToXsdFile * e.g. "dbsql2xml.xsd" * @param namesOfGlobalVariables * e.g. "$gvG01#$gvG02#$gvG03" or "myVarX#myVarY#myVarZ" * @param valuesOfGlobalVariables * e.f "01#JohnSmith#2005-05-10" <br /> * <br /> * token, which delimites names and values of global variables, is * set in mapping XML file inside element * <code>tokenForCommandLineStringArrays</code> <br /> * it can be single or multiple character <br /> * token is the same for names and values of global variables <br /> * <br /> * So example of creating <code>dbsql2xml</code> object is: <br /> * <code>dbsql2xml myDbSql2Xml = new dbsql2xml("treeXMLMapping.xml", "dbsql2xml.xsd", "$gvG01", "001");</code> * <br /> * See example in distribution (standalone application and servlet). */ public Dbsql2xml(String pathToMappingXmlFile, String pathToXsdFile, String namesOfGlobalVariables, String valuesOfGlobalVariables) { this.pathToMappingXmlFile = pathToMappingXmlFile; this.pathToXsdFile = pathToXsdFile; this.namesOfGlobalVariables = namesOfGlobalVariables; this.valuesOfGlobalVariables = valuesOfGlobalVariables; this.pathToOutputXmlFile = null; this.connection = null; this.connnectionPassed = false; log.debug("CreatingDbsql2xmlwith:" + "\npathToMappingXmlFile=" + pathToMappingXmlFile + "\npathToXsdFile=" + pathToXsdFile + "\nnamesOfGlobalVariables=" + namesOfGlobalVariables + "\nvaluesOfGlobalVariables=" + valuesOfGlobalVariables + "\npathToOutputXmlFile=" + pathToOutputXmlFile); } /** * Creates a <code>dbsql2xml</code> for output to <code>String</code>, * <code>Document</code> and <code>System.out</code> with * <code>Connection</code> already defined. * * @param pathToMappingXmlFile * e.g "treeXMLMapping.xml" * @param pathToXsdFile * e.g. "dbsql2xml.xsd" * @param namesOfGlobalVariables * e.g. "$gvG01#$gvG02#$gvG03" or "myVarX#myVarY#myVarZ" * @param valuesOfGlobalVariables * e.g. "01#JohnSmith#2005-05-10" * @param connection * <br /> * <br /> * token, which delimites names and values of global variables, is * set in mapping XML file inside element * <code>tokenForCommandLineStringArrays</code> <br /> * it can be single or multiple character <br /> * token is the same for names and values of global variables <br /> * <br /> * So example of creating <code>dbsql2xml</code> object is: <br /> * <code>dbsql2xml myDbSql2Xml = new dbsql2xml("treeXMLMapping.xml", "dbsql2xml.xsd", "$gvG01", "001");</code> * <br /> * See example in distribution (standalone application and servlet). */ public Dbsql2xml(String pathToMappingXmlFile, String pathToXsdFile, String namesOfGlobalVariables, String valuesOfGlobalVariables, Connection connection) throws Exception { this.pathToMappingXmlFile = pathToMappingXmlFile; this.pathToXsdFile = pathToXsdFile; this.namesOfGlobalVariables = namesOfGlobalVariables; this.valuesOfGlobalVariables = valuesOfGlobalVariables; this.pathToOutputXmlFile = null; this.connection = connection; log.debug("CreatingDbsql2xmlwith:" + "\npathToMappingXmlFile=" + pathToMappingXmlFile + "\npathToXsdFile=" + pathToXsdFile + "\nnamesOfGlobalVariables=" + namesOfGlobalVariables + "\nvaluesOfGlobalVariables=" + valuesOfGlobalVariables + "\npathToOutputXmlFile=" + pathToOutputXmlFile); } private void doExport(OutputStream out) { long startTime = System.currentTimeMillis(); try { checkInputParameters(); // load mapping (configuration) XML file Document mapping = createMappingFromFile(); // initialize XPath for future use xPathHelper = new XPathHelper(); // load global variables from constructors parameters and mapping XML file loadGlobalVariables(namesOfGlobalVariables, valuesOfGlobalVariables, mapping); // create output XML writer writer = XMLOutputFactory.newInstance().createXMLStreamWriter(out); writer.writeStartDocument(); // create root element of output XML document String rootElementName = xPathHelper.getString("config/rootElementName", mapping); if (rootElementName == null || rootElementName.trim().length() == 0) { rootElementName = "dbsql2xml"; } writer.writeStartElement(rootElementName); applicationInfo = initApplicationInfo(); writer.writeComment(applicationInfo); globalCharsetName = xPathHelper.getString("config/globalCharsetName", mapping); if (connection == null) { if (jdbcDriver == null || jdbcURL == null || jdbcUserName == null || jdbcPassword == null) { jdbcDriver = xPathHelper.getString("config/connectionProperties/jdbcDriver", mapping); jdbcURL = xPathHelper.getString("config/connectionProperties/jdbcURL", mapping); jdbcUserName = xPathHelper.getString("config/connectionProperties/jdbcUserName", mapping); jdbcPassword = xPathHelper.getString("config/connectionProperties/jdbcPassword", mapping); } connection = getConnection(jdbcDriver, jdbcURL, jdbcUserName, jdbcPassword); } multiStatementDriver = xPathHelper.getString("config/connectionProperties/multiStatementDriver", mapping).equalsIgnoreCase("true"); // load data from database to hierarchical XML document Element topLevelTableElement = xPathHelper.getElement("/config/table", mapping); processTableElement(topLevelTableElement); // end XML document writer.writeEndElement(); writer.writeEndDocument(); writer.flush(); writer.close(); // append to or process output XML document XSLT or CSS (if any) in // mapping file// broken - we'd need to write the document to a byte array, then convert the byte array to a Document before calling this function// Element processingInstructionsElement = xPathHelper.getElement("config/processingInstructions", mapping);// doProcessingInstructions(processingInstructionsElement, rootElement); // If we didn't get a connection from the client then close it. if (!this.connnectionPassed) { connection.close(); connection = null; } } catch (Exception e) { log.error("Error!", e); } finally { System.gc(); } log.debug("Ittook" + (System.currentTimeMillis() - startTime) + "mstocreatethexml"); xmlTime += (System.currentTimeMillis() - startTime); } private String initApplicationInfo() { String retVal = ""; retVal = "The\"dbsql2xml\" is Java tool (class) for transforming (export) relational databases into hierarchical XML.\nFor more information, see http://sourceforge.net/projects/dbsql2xml/.\n"+"It has been modified by Dallan Quass to work for very large documents and MySQL";returnretVal;}privatevoidcheckInputParameters()throwsException{try{if(pathToMappingXmlFile==null|pathToMappingXmlFile==""){thrownewException("NomappingXMLfilespecified.");}if(pathToXsdFile==null|pathToXsdFile==""){thrownewException("NoXMLSchemaspecified.");}if(namesOfGlobalVariables==null|valuesOfGlobalVariables==null){namesOfGlobalVariables="";valuesOfGlobalVariables="";}}catch(Exceptione){log.error("pathToMappingXmlFile=\""+pathToMappingXmlFile+"\",pathToXsdFile=\""+pathToXsdFile+"\",namesOfGlobalVariables=\""+namesOfGlobalVariables+"\",valuesOfGlobalVariables=\""+valuesOfGlobalVariables+"\"");log.error("errorincheckInputParameters");throwe;}}/** * Output results to <code>File</code>. It is intended for standalone * export (transformation, extraction) application. Output encoding is in * UTF-8. */publicvoiddoExportIntoFile()throwsException{try{if(pathToOutputXmlFile==null|pathToOutputXmlFile==""){thrownewException("Itlookslikenotfourparameterswasgiven-nofileforoutput");}else{longstartTime=System.currentTimeMillis();OutputStreamout=newFileOutputStream(pathToOutputXmlFile);doExport(out);out.close();// TransformerFactorytransformerFactory=TransformerFactory.newInstance();// Transformertransformer=transformerFactory.newTransformer();// Sourcesource=newDOMSource(outDocument);// StreamResultstreamResult=newStreamResult(newFile(pathToOutputXmlFile));// transformer.transform(source,streamResult);log.debug("Wrotefileto"+pathToOutputXmlFile);log.debug("Ittook"+(System.currentTimeMillis()-startTime)+"mstoprocessthexml");totalTime+=(System.currentTimeMillis()-startTime);}}catch(Exceptione){log.error("errorindoExportIntoFile",e);throwe;}}/** * Output results to <code>String</code>. It is intended for Java servlets. * Output encoding is in UTF-8. */publicStringdoExportIntoString()throwsException{try{ByteArrayOutputStreambyteArrayOutputStream=newByteArrayOutputStream();doExport(byteArrayOutputStream);// TransformerFactorytransformerFactory=TransformerFactory.newInstance();// Transformertransformer=transformerFactory.newTransformer();// Sourcesource=newDOMSource(outDocument);// StreamResultstreamResult=newStreamResult(byteArrayOutputStream);// transformer.transform(source,streamResult);returnbyteArrayOutputStream.toString("UTF-8");//outputisalwaysin//UTF-8}catch(Exceptione){log.error("errorindoExportIntoString",e);throwe;}}/** * Output results to <code>System.out</code>. It is intended for debugging * purposes on systems with console. Output encoding is in UTF-8. */publicvoiddoExportIntoStandardOutput()throwsException{try{System.out.println(doExportIntoString());}catch(Exceptione){log.error("errorindoExportIntoStandardOutput",e);throwe;}}/** * Output results to <code>Document</code>. It is intended for application * integration into other XML related ones. Output encoding is in UTF-8. *///broken-weneedtowritethedocumenttoabytearray,thenconvertthebytearraytoaDocument//publicDocumentdoExportIntoDocument()throwsException{// try{// doExport();// return(outDocument);// }//catch(Exceptione){// log.error("errorindoExportIntoString",e);// throwe;// }//}privatevoidloadGlobalVariables(StringnamesOfGlobalVariables,StringvaluesOfGlobalVariables,Documentdocument)throwsException{try{//loadglobalvariablesgivenbymappingfileNodeListnodeList=xPathHelper.getNodeList("config/globalVariables/globalVariable",document);for(inti=0;i<nodeList.getLength();i++){globalVariables.put(xPathHelper.getString("@name",(Node)nodeList.item(i)),xPathHelper.getString("self::node()", (Node) nodeList.item(i))); } // load global variables given by constructor String token = xPathHelper.getString("config/tokenForCommandLineStringArrays", document); String[] globalVariablesNames = namesOfGlobalVariables.split(token); String[] globalVariablesValues = valuesOfGlobalVariables.split(token); if (globalVariablesNames.length == globalVariablesValues.length) { for (int i = 0; i < globalVariablesNames.length; i++) { globalVariables.put(globalVariablesNames[i], globalVariablesValues[i]);// global // variables // is // HashMap } } else { throw new Exception("Constructorparametersglobalvariablesnamesandvaluesdoesnotmatchincount."); } } catch (Exception e) { log.error("errorinloadGlobalVariables", e); throw e; } } private Document createMappingFromFile() throws Exception {// path to file is // global String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage"; String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema"; String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource"; try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); // validate against XML Schema in dbsql2xml.xsd documentBuilderFactory.setNamespaceAware(true); String version = System.getProperty("java.version"); //Essentially make sure we are jdk 1.5 or above to do the special stuff. if (isJaxpIncluded(version)) { documentBuilderFactory.setValidating(false);// mapping file will be validated against definition in XML Schema Unfortunately saxon doesn't support this. BEWARE documentBuilderFactory.setXIncludeAware(true);// mapping file can use XInclude documentBuilderFactory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA); documentBuilderFactory.setAttribute(JAXP_SCHEMA_SOURCE, new File(pathToXsdFile)); } DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(new File(pathToMappingXmlFile)); return document; } catch (Exception e) { e.printStackTrace(); log.error("errorincreateDocumentFromFile", e); throw e; } }// private Document createNewDocument() throws Exception {// try {// DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();// DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();// Document document = documentBuilder.newDocument();// return document;// }// catch (Exception e) {// log.error("errorincreateNewDocument", e);// throw e;// }// }// private void doProcessingInstructions(Element processingInstructionsElement, Element rootElement) throws Exception {// try {// String xslt = xPathHelper.getString("xslt", processingInstructionsElement);// String css = xPathHelper.getString("css", processingInstructionsElement);// if (!xslt.equals("")) {// if (0 == 1) {// // not now - to be done processing XML using XSLT in this program// }// else {// ProcessingInstruction xmlstylesheet = outDocument.createProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\""+xslt+"\"");// outDocument.insertBefore(xmlstylesheet,rootElement);// }//}//if(!css.equals("")){// ProcessingInstructionxmlstylesheet=outDocument.createProcessingInstruction("xml-stylesheet","type=\"text/css\"href=\""+css+"\"");// outDocument.insertBefore(xmlstylesheet,rootElement);// }//}//catch(Exceptione){// log.error("errorindoProcessingInstructions",e);// throwe;// }//}//processTABLEelementsshouldbebettercommentedprivatevoidprocessTableElement(ElementtableElement)throwsException{//Whatshouldthiselementbenamed.StringtableElementName=tableElement.getAttribute("xmlName");//getSQLSELECTstatementtobeusedforquerycolumnvaluesStringtableSql=tableElement.getAttribute("sql");Stringprepared=tableElement.getAttribute("isPrepared");booleanisPrepared=false;ArrayListparamVals=newArrayList();if(prepared!=null&&prepared.trim().length()>0){isPrepared=Boolean.parseBoolean(prepared);}if(isPrepared){//Processallthe<prepared...>elementstocreatereplacementsNodeListnl=tableElement.getChildNodes();for(inti=0;i<nl.getLength();i++){if(nl.item(i).getNodeName()=="replacement"){Elementelem=(Element)nl.item(i);Stringorder=elem.getAttribute("order");Stringtype=elem.getAttribute("paramType");//Notreallyavalueyet,buttheglobalvariabletouse.Stringvalue=elem.getAttribute("parameter");Stringtemplate=elem.getAttribute("conversionTemplate");ReplacementValuerv=newReplacementValue();rv.setOrder(Integer.parseInt(order));rv.setType(type);rv.setValue(value);rv.setConversionTemplate(template);paramVals.add(rv);}}}//replaceglobalvariablesnamesbytheirvaluesStatementstatement=null;PreparedStatementpreparedStatement=null;ResultSetresultSet=null;try{if(isPrepared){preparedStatement=getPreparedStatement(connection,tableSql);resultSet=getResultSet(preparedStatement,paramVals);}else{tableSql=replaceGlobalVariable(tableSql);statement=getStatement(connection);resultSet=getResultSet(statement,tableSql);}while(resultSet.next()){//eachrecordisencapsulatedbytablexmlNamewriter.writeStartElement(tableElementName);// ElementnewElement=outDocument.createElement(tableElementName);NodeListnl=tableElement.getChildNodes();//walkthrougheachcolumnoftableelementfor(inti=0;i<nl.getLength();i++){//XSDensurescolumnsfirst,tablesecondif(nl.item(i).getNodeName()=="column"){processColumnElement((Element)nl.item(i),resultSet);}if(nl.item(i).getNodeName()=="replacement"){}if(nl.item(i).getNodeName()=="table"){processTableElement((Element)nl.item(i));}}writer.writeEndElement();//parentElement.appendChild(newElement);}}catch(Exceptione){log.error("tableSql=\""+tableSql+"\",multiStatementDriver=\""+multiStatementDriver+"\"");log.error("errorinprocessTableElement",e);throwe;}finally{//DoSomecleanupif(resultSet!=null){try{resultSet.close();}catch(Exceptionignored){}}if(statement!=null&&!multiStatementDriver){try{statement.close();}catch(Exceptionignored){}}if(preparedStatement!=null){try{preparedStatement.close();}catch(Exceptionignored){}}}}//processCOLUMNelementsshouldbebettercommentedprivatevoidprocessColumnElement(ElementcolumnElement,ResultSetresultSet)throwsException{StringcolumnElementName=columnElement.getAttribute("xmlName");StringcolumnElementValue=columnElement.getAttribute("sqlName");StringcolumnGlobalVariableName=columnElement.getAttribute("globalVariableName");StringcharsetName=columnElement.getAttribute("charsetName");if(charsetName==null|charsetName==""){charsetName=globalCharsetName;}try{intcolumnIndex=resultSet.findColumn(columnElementValue);//indexofthisattributeintheResultSetStringcolumnValue=getColumnValueAsString(resultSet,columnIndex,charsetName);//isvalueofthiscolumnusedinsidefollowingSQLSELECTstatements?asglobalvariable...if(columnGlobalVariableName!=null){globalVariables.put(columnGlobalVariableName,columnValue);}//ElementnewElement=outDocument.createElement(columnElementName);//TextnewText=outDocument.createTextNode(columnValue);//newElement.appendChild(newText);//parentElement.appendChild(newElement);writer.writeStartElement(columnElementName);writer.writeCharacters(columnValue);writer.writeEndElement();}catch(Exceptione){log.error("xmlName=\""+columnElementName+"\",sqlName=\""+columnElementValue+"\",globalVariableName=\""+columnGlobalVariableName+"\",charsetName=\""+charsetName+"\"");log.error("errorinprocessColumnElement",e);throwe;}}privatevoidsetReplacementValue(PreparedStatementps,intorder,Stringtype,StringconversionTemplate,StringrValue)throwsException{Stringvalue=(String)globalVariables.get(rValue);if(type.toLowerCase().trim().equals("string")){ps.setString(order,value);}elseif(type.toLowerCase().trim().equals("int")){ps.setInt(order,Integer.parseInt(value));}elseif(type.toLowerCase().trim().equals("long")){ps.setLong(order,Long.parseLong(value));}elseif(type.toLowerCase().trim().equals("double")){ps.setDouble(order,Double.parseDouble(value));}elseif(type.toLowerCase().trim().equals("float")){ps.setFloat(order,Float.parseFloat(value));}elseif(type.toLowerCase().trim().equals("date")){SimpleDateFormatsdf=newSimpleDateFormat(conversionTemplate);Dated=sdf.parse(value);ps.setDate(order,newjava.sql.Date(d.getTime()));sdf=null;}}//RegExpchangeglobalvariablesinSQLSELECTstatementusingregularexpressionprivateStringreplaceGlobalVariable(StringtableSql){Setset=globalVariables.keySet();Iteratoriterator=set.iterator();while(iterator.hasNext()){//walkthrougheachglobalvariablespairStringkey=(String)iterator.next();Stringvalue=(String)globalVariables.get(key);//herecanbeanerrorinRegEx-shouldbetestedbyuserstableSql=tableSql.replaceAll("\\"+key+"{1,}", value);// replace key // by value }// end_while return tableSql; } // SQL generic functions private Connection getConnection(String jdbcDriver, String jdbcUrl, String jdbcUserName, String jdbcPassword) throws Exception { try { Class.forName(jdbcDriver); Connection connection = DriverManager.getConnection(jdbcUrl, jdbcUserName, jdbcPassword); return connection; } catch (Exception e) { log.error("jdbcDriver=\""+jdbcDriver+"\", jdbcUrl=\""+jdbcUrl+"\", jdbcUserName and jdbcPassword are not logged");log.error("error in getConnection",e);throwe;}}privateStatementgetStatement(Connectionconnection)throwsException{try{//if-elsefordrivers,whichcannothavemultipleResultSet-speroneStatementif(!multiStatementDriver){returnconnection.createStatement();}else{if(globalStatement==null){globalStatement=connection.createStatement();}returnglobalStatement;}}catch(Exceptione){e.printStackTrace();log.error("connection=\""+connection+"\"");log.error("erroringetStatement",e);throwe;}}privatePreparedStatementgetPreparedStatement(Connectionconnection,StringsqlSelect)throwsException{try{returnconnection.prepareStatement(sqlSelect);}catch(Exceptione){e.printStackTrace();log.error("connection=\""+connection+"\",sqlSelect=\""+sqlSelect+"\"");log.error("erroringetPreparedStatement",e);throwe;}}/** * * The standard for using regular statements * * @param connection the sql connection to use * @param sqlSelect the sql to execute - already replaced from global vals * @return the result set from executing the statement * @throws Exception */privateResultSetgetResultSet(Statementstatement,StringsqlSelect)throwsException{ResultSetretVal=null;try{retVal=statement.executeQuery(sqlSelect);}catch(Exceptione){log.error("statement=\""+statement+"\",sqlSelect=\""+sqlSelect+"\",multiStatementDriver=\""+multiStatementDriver+"\"");log.error("erroringetResultSet",e);throwe;}returnretVal;}/** * * This implementation is specifically for using prepared statements. * * @param connection The sql connection to use * @param sqlSelect the sql to execute * @param paramVals the arraylist of parameters * @return the result set from executing the query * @throws Exception */privateResultSetgetResultSet(PreparedStatementpreparedStatement,ArrayListparamVals)throwsException{ResultSetretVal=null;try{if(paramVals!=null&¶mVals.size()>0){for(inti=0;i<paramVals.size();i++){ReplacementValuerv=(ReplacementValue)paramVals.get(i);this.setReplacementValue(preparedStatement,rv.getOrder(),rv.getType(),rv.getConversionTemplate(),(String)rv.getValue());}}retVal=preparedStatement.executeQuery();}catch(Exceptione){log.error("connection=\""+connection+"\",multiStatementDriver=\""+multiStatementDriver+"\"");log.error("erroringetResultSet",e);throwe;}returnretVal;}//TODOallowdifferenttypesmainlybooleanforchar(1)thatis"Y","y","N","n","0","1","T","t","F"or"f"forinstanceprivateStringgetColumnValueAsString(ResultSetresultSet,intcolumnIndex,StringcharsetName)throwsException{ResultSetMetaDataresultSetMetaData=resultSet.getMetaData();try{switch(resultSetMetaData.getColumnType(columnIndex)){casejava.sql.Types.VARCHAR:casejava.sql.Types.CHAR:casejava.sql.Types.LONGVARCHAR://notused-seemsliketheJDBCdrivershouldreturnthestringinthecorrectcharacterset//byte[]byteArray=resultSet.getBytes(columnIndex);// if(byteArray==null||resultSet.wasNull()){// return"null";// }//else{// StringstringFromChar=newString(byteArray,charsetName);// returnstringFromChar;// }//end_if-elseStringstring=resultSet.getString(columnIndex);if(resultSet.wasNull()){return"";}else{returnstring;}//end_if-elsecasejava.sql.Types.DOUBLE:casejava.sql.Types.INTEGER:casejava.sql.Types.BIGINT:casejava.sql.Types.TINYINT:casejava.sql.Types.SMALLINT:casejava.sql.Types.REAL:casejava.sql.Types.FLOAT:casejava.sql.Types.DECIMAL:casejava.sql.Types.NUMERIC:casejava.sql.Types.BIT:StringstringFromNumeric=resultSet.getString(columnIndex);if(resultSet.wasNull()){return"";}else{returnstringFromNumeric;}//end_if-elsecasejava.sql.Types.BINARY:casejava.sql.Types.VARBINARY:casejava.sql.Types.LONGVARBINARY:StringstringFromBinary=resultSet.getString(columnIndex);if(resultSet.wasNull()){return"";}else{returnstringFromBinary;}//end_if-elsecasejava.sql.Types.DATE:java.sql.Datedate=resultSet.getDate(columnIndex);if(resultSet.wasNull()){return"";}else{returndate.toString();}//end_if-elsecasejava.sql.Types.TIME:java.sql.Timetime=resultSet.getTime(columnIndex);if(resultSet.wasNull()){return"";}else{returntime.toString();}//end_if-elsecasejava.sql.Types.TIMESTAMP:java.sql.Timestamptimestamp=resultSet.getTimestamp(columnIndex);if(resultSet.wasNull()){return"";}else{returntimestamp.toString();}//end_if-elsedefault:return"unsupported data type (CLOB and BLOB should be, ARRAY, REF, STRUCT, JAVA OBJECT hard to be)";}//end_switch}catch(Exceptione){log.error("resultSet=\""+resultSet+"\",columnindex=\""+columnIndex+"\",columntype=\""+resultSetMetaData.getColumnType(columnIndex)+"\",charsetName=\""+charsetName+"\"");log.error("erroringetColumnValueAsString",e);throwe;}}publicStringgetValuesOfGlobalVariables(){returnvaluesOfGlobalVariables;}publicvoidsetValuesOfGlobalVariables(StringvaluesOfGlobalVariables){this.valuesOfGlobalVariables=valuesOfGlobalVariables;}publicStringgetPathToOutputXmlFile(){returnpathToOutputXmlFile;}publicvoidsetPathToOutputXmlFile(StringpathToOutputXmlFile){this.pathToOutputXmlFile=pathToOutputXmlFile;if(log.isDebugEnabled()){log.debug("Pathtooutputxmlis"+pathToOutputXmlFile);}}publiclonggetTotalTime(){returntotalTime;}publicvoidsetTotalTime(longtotaltime){this.totalTime=totaltime;}publiclonggetXmlTime(){returnxmlTime;}publicvoidsetXmlTime(longxmltime){this.xmlTime=xmltime;}privatestaticbooleanisJaxpIncluded(StringversionString){booleanretVal=true;if(versionString!=null&&versionString.trim().length()>=3){versionString=versionString.substring(2,3);intversion=Integer.parseInt(versionString);if(version>=5){retVal=true;}}returnretVal;}classReplacementValue{privateint order;privateStringtype;privateObjectvalue;privateStringconversionTemplate;publicvoidsetOrder(intorder){this.order=order;}publicintgetOrder(){returnthis.order;}publicvoidsetType(Stringtype){this.type=type;}publicStringgetType(){returnthis.type;}publicvoidsetValue(Objectvalue){this.value=value;}publicObjectgetValue(){returnthis.value;}publicvoidsetConversionTemplate(Stringtemplate){this.conversionTemplate=template;}publicStringgetConversionTemplate(){returnthis.conversionTemplate;}}}
If you would like to refer to this comment somewhere else in this project, copy and paste the following link:
FWIW, after making the changes mentioned earlier so it would work better with MySQL, I've also modified it so it uses XMLStreamWriter, allowing it to process larger files. Here's the updated Dbsql2xml.java file containing the changes for both MySQL and XMLStreamWriter: