Inserting XML data into MySQL database

寵の児 提交于 2019-12-11 23:22:23

问题


I am trying to insert XML data into a MySQL database. The SAX parser I wrote works on its own when tested. However, whenever I try to insert records into the database, I get a NullPointerException even though I made sure to assign values to workflow elements that were null. Here is my database Table code. package database;

//STEP 1. Import required packages
import java.sql.*;
import java.io.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;

public class Table {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
static final String DB_URL = "jdbc:mysql://baldwin.isri.cmu.edu/SciSIP";

//  Database credentials
static final String USER = "user";
static final String PASS = "pass";

public Table()  {

}

public void createTable()  {    
    Connection con = null;
    Statement stmt = null;
    try{
        //STEP 2: Register JDBC driver
        Class.forName("com.mysql.jdbc.Driver");

        //STEP 3: Open a connection
        System.out.println("Connecting to a selected database...");
        con = DriverManager.getConnection(DB_URL, USER, PASS);
        System.out.println("Connected database successfully...");

        //STEP 4: Execute a query
        System.out.println("Creating table in given database...");
        stmt = con.createStatement();

        String sql = "CREATE TABLE IF NOT EXISTS workflow" +
                "(id INTEGER not NULL AUTO_INCREMENT, " +
                " annotationBean VARCHAR(255), " + 
                " date VARCHAR(255), " + 
                " text VARCHAR(255), " +
                " identification VARCHAR(255), " +
                " PRIMARY KEY ( id ))"; 

        stmt.executeUpdate(sql);
        System.out.println("Created table in given database...");
    } catch(SQLException se) {
        //Handle errors for JDBC
        se.printStackTrace();
    } catch(Exception e) {
        //Handle errors for Class.forName
        e.printStackTrace();
    } finally {
        //finally block used to close resources
        try {
            if(stmt != null)
                con.close();
        } catch(SQLException se) {
        }// do nothing
        try {
            if(con != null)
                con.close();
        } catch(SQLException se) {
            se.printStackTrace();
        }//end finally try
    }//end try
    System.out.println("Goodbye!");
}

public void insertRecord(String annotationBean, String date, String text, String identification)  {
    Connection con = null;
    Statement stmt = null;
    try {
        Class.forName("com.mysql.jdbc.Driver"); //Load the driver           
        con = DriverManager.getConnection(DB_URL, USER, PASS);
        stmt = con.createStatement();
        String sql = "INSERT INTO `workflow` VALUES ('"+annotationBean+"', '"+date+"', '"+text+"', '"+identification+"')";
        stmt.execute(sql); //Insert a row
        System.out.println("Record Inserted into Database...");
    } catch(SQLException se) {
        //Handle errors for JDBC
        se.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        //finally block used to close resources
        try {
            if(stmt != null)
                con.close();
        } catch(SQLException se) {
        }// do nothing
        try {
            if(con != null)
                con.close();
        } catch(SQLException se) {
            se.printStackTrace();
        }//end finally try
    }//end try
}

Here is my parser code with the insert record statement.

package parser;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import database.Table;

public class XML_Parser_SAX extends DefaultHandler{
List aWorkflow;
private String tempVal;
//to maintain context
private Workflow tempWorkflow;

public XML_Parser_SAX(){
    aWorkflow = new ArrayList();
}

public void runExample() {
    parseDocument();
    printData();
}

private void parseDocument() {
    //get a factory
    SAXParserFactory spf = SAXParserFactory.newInstance();
    try {

        //get a new instance of parser
        SAXParser sp = spf.newSAXParser();

        //parse the file and also register this class for call backs
        sp.parse("workflow.xml", this);

    }catch(SAXException se) {
        se.printStackTrace();
    }catch(ParserConfigurationException pce) {
        pce.printStackTrace();
    }catch (IOException ie) {
        ie.printStackTrace();
    }
}

/**
 * Iterate through the list and print
 * the contents
 */
private void printData(){

    System.out.println("Number of Tasks in Workflow: '" + aWorkflow.size() + "'.");

    Iterator it = aWorkflow.iterator();
    while(it.hasNext()) {
        System.out.println(it.next().toString());
    }
}


//Event Handlers
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
    //reset
    tempVal = "";
    if(qName.equalsIgnoreCase("annotationBean")) {
        //create a new instance of employee
        tempWorkflow = new Workflow();
        tempWorkflow.setAnnotationBean(attributes.getValue("class"));
        System.out.println("class");
    }
}


public void characters(char[] ch, int start, int length) throws SAXException {
    tempVal = new String(ch,start,length);
}

public void endElement(String uri, String localName, String qName) throws SAXException {

    if(qName.equalsIgnoreCase("annotationBean")) {
        //add it to the list
        aWorkflow.add(tempWorkflow);
        System.out.println("annotationBean");

    } else if (qName.equalsIgnoreCase("date")) {
        if (tempVal != null)  {
            tempWorkflow.setDate(tempVal);
        }
        else  {
            tempWorkflow.setDate("null");
        }
        System.out.println(tempWorkflow.getDate());
    } else if (qName.equalsIgnoreCase("text")) {
        if (tempVal != null)  {
            tempWorkflow.setText(tempVal);
        }
        else  {
            tempWorkflow.setText("null");
        }
        System.out.println(tempWorkflow.getText());
    } else if (qName.equalsIgnoreCase("identification")) {
        if (tempVal != null)  {
            tempWorkflow.setIdentification(tempVal);
        }
        else  {
            tempWorkflow.setIdentification("null");
        }
        System.out.println(tempWorkflow.getIdentification());
    }
    Table t = new Table();
    //t.createTable();
    t.insertRecord(tempWorkflow.getAnnotationBean(), tempWorkflow.getDate(), tempWorkflow.getText(), tempWorkflow.getIdentification());
}

public static void main(String[] args){
    XML_Parser_SAX parse = new XML_Parser_SAX();
    parse.runExample();
}

}

Can someone please tell me why this is giving me the NullPointerException? Thanks in advance!!!

Here is the stacktrace:

Exception in thread "main" java.lang.NullPointerException
at parser.XML_Parser_SAX.endElement(XML_Parser_SAX.java:126)
at     com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.endElement(AbstractSAXParser.java:606)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanEndElement(XMLDocumentFragmentScannerImpl.java:1741)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2898)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:607)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:488)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:835)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:764)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:123)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1210)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:568)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl.parse(SAXParserImpl.java:302)
at javax.xml.parsers.SAXParser.parse(SAXParser.java:274)
at parser.XML_Parser_SAX.parseDocument(XML_Parser_SAX.java:49)
at parser.XML_Parser_SAX.runExample(XML_Parser_SAX.java:35)
at parser.XML_Parser_SAX.main(XML_Parser_SAX.java:131)

Yes, workflow.xml exists. Here is a copy of it below.

<workflow xmlns="http://taverna.sf.net/2008/xml/t2flow" version="1" producedBy="taverna-      2.4.0"><dataflow id="8781d5f4-d0ba-48a8-a1d1-14281bd8a917" role="top"><name>Hello_World</name>       <inputPorts /><outputPorts><port><name>greeting</name><annotations /></port></outputPorts>       <processors><processor><name>hello</name><inputPorts /><outputPorts><port><name>value</name>       <depth>0</depth><granularDepth>0</granularDepth></port></outputPorts><annotations />       <activities><activity><raven><group>net.sf.taverna.t2.activities</group>      <artifact>stringconstant-activity</artifact><version>1.4</version></raven>     <class>net.sf.taverna.t2.activities.stringconstant.StringConstantActivity</class><inputMap />    <outputMap><map from="value" to="value" /></outputMap><configBean encoding="xstream">    <net.sf.taverna.t2.activities.stringconstant.StringConstantConfigurationBean xmlns="">
  <value>Hello, World!</value>
 </net.sf.taverna.t2.activities.stringconstant.StringConstantConfigurationBean></configBean>    <annotations /></activity></activities><dispatchStack><dispatchLayer><raven>        <group>net.sf.taverna.t2.core</group><artifact>workflowmodel-impl</artifact>        <version>1.4</version></raven>       <class>net.sf.taverna.t2.workflowmodel.processor.dispatch.layers.Parallelize</class>        <configBean encoding="xstream">        <net.sf.taverna.t2.workflowmodel.processor.dispatch.layers.ParallelizeConfig xmlns="">
  <maxJobs>1</maxJobs>
    </net.sf.taverna.t2.workflowmodel.processor.dispatch.layers.ParallelizeConfig>    </configBean></dispatchLayer><dispatchLayer><raven><group>net.sf.taverna.t2.core</group>    <artifact>workflowmodel-impl</artifact><version>1.4</version></raven>    <class>net.sf.taverna.t2.workflowmodel.processor.dispatch.layers.ErrorBounce</class>    <configBean encoding="xstream"><null xmlns="" /></configBean></dispatchLayer><dispatchLayer>    <raven><group>net.sf.taverna.t2.core</group><artifact>workflowmodel-impl</artifact>    <version>1.4</version></raven>    <class>net.sf.taverna.t2.workflowmodel.processor.dispatch.layers.Failover</class><configBean     encoding="xstream"><null xmlns="" /></configBean></dispatchLayer><dispatchLayer><raven>    <group>net.sf.taverna.t2.core</group><artifact>workflowmodel-impl</artifact>    <version>1.4</version></raven>    <class>net.sf.taverna.t2.workflowmodel.processor.dispatch.layers.Retry</class><configBean     encoding="xstream"><net.sf.taverna.t2.workflowmodel.processor.dispatch.layers.RetryConfig     xmlns="">
  <backoffFactor>1.0</backoffFactor>
  <initialDelay>1000</initialDelay>
  <maxDelay>5000</maxDelay>
  <maxRetries>0</maxRetries>
</net.sf.taverna.t2.workflowmodel.processor.dispatch.layers.RetryConfig></configBean>    </dispatchLayer><dispatchLayer><raven><group>net.sf.taverna.t2.core</group>        <artifact>workflowmodel-impl</artifact><version>1.4</version></raven>        <class>net.sf.taverna.t2.workflowmodel.processor.dispatch.layers.Invoke</class><configBean         encoding="xstream"><null xmlns="" /></configBean></dispatchLayer></dispatchStack>       <iterationStrategyStack><iteration><strategy /></iteration></iterationStrategyStack>         </processor></processors><conditions /><datalinks><datalink><sink type="dataflow">        <port>greeting</port></sink><source type="processor"><processor>hello</processor>       <port>value</port></source></datalink></datalinks><annotations><annotation_chain         encoding="xstream"><net.sf.taverna.t2.annotation.AnnotationChainImpl xmlns="">
  <annotationAssertions>
     <net.sf.taverna.t2.annotation.AnnotationAssertionImpl>
       <annotationBean class="net.sf.taverna.t2.annotation.annotationbeans.Author">
        <text>Stian Soiland-Reyes</text>
       </annotationBean>
       <date>2012-01-03 15:10:48.73 GMT</date>
      <creators />
       <curationEventList />
     </net.sf.taverna.t2.annotation.AnnotationAssertionImpl>
  </annotationAssertions>
 </net.sf.taverna.t2.annotation.AnnotationChainImpl></annotation_chain><annotation_chain     encoding="xstream"><net.sf.taverna.t2.annotation.AnnotationChainImpl xmlns="">
   <annotationAssertions>
     <net.sf.taverna.t2.annotation.AnnotationAssertionImpl>
      <annotationBean      class="net.sf.taverna.t2.annotation.annotationbeans.DescriptiveTitle">
         <text>Hello World</text>
       </annotationBean>
           <date>2012-01-03 15:10:54.167 GMT</date>
       <creators />
  <curationEventList />
     </net.sf.taverna.t2.annotation.AnnotationAssertionImpl>
  </annotationAssertions>
     </net.sf.taverna.t2.annotation.AnnotationChainImpl></annotation_chain>            <annotation_chain_2_2 encoding="xstream"><net.sf.taverna.t2.annotation.AnnotationChainImpl        xmlns="">
  <annotationAssertions>
    <net.sf.taverna.t2.annotation.AnnotationAssertionImpl>
      <annotationBean     class="net.sf.taverna.t2.annotation.annotationbeans.IdentificationAssertion">
        <identification>8781d5f4-d0ba-48a8-a1d1-14281bd8a917</identification>
      </annotationBean>
      <date>2012-01-03 15:12:21.684 GMT</date>
  <creators />
  <curationEventList />
</net.sf.taverna.t2.annotation.AnnotationAssertionImpl>

<text>One of the simplest workflows possible. No workflow input ports, a         single          workflow output port "greeting",  outputting "Hello, world!" as produced by the        String          Constant "hello".</text>
                </annotationBean>
            <date>2012-01-03 15:12:15.643 GMT</date>
           <creators />
           <curationEventList />
        </net.sf.taverna.t2.annotation.AnnotationAssertionImpl>
      </annotationAssertions>
       </net.sf.taverna.t2.annotation.AnnotationChainImpl></annotation_chain></annotations >         
 </dataflow></workflow>

回答1:


Your tempWorkflow is set to null.

Your startElement only builds a tempWorkflow when it gets an annotationBean startTag, but it executes your failing element on ANY end tag. So when it gets </configBean> it will fail.

You need to have corresponding start and end actions =you have to add a lot more start actions. And you also have to check that everythingis properly initialized at the right places.

It will help a lot if you put in logging statements (e.g. log4J) such as:

LOG.debug("start-tag tempWorkFlow");

This will allow you to work out exactly when the code is being called.



来源:https://stackoverflow.com/questions/13894036/inserting-xml-data-into-mysql-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!