Einfügen von XML-Daten in MySQL-Datenbank

Ich versuche, einfügen von XML-Daten in eine MySQL-Datenbank. Der SAX-parser, die ich schrieb, funktioniert auf seine eigene, wenn getestet. Aber immer, wenn ich versuche, um Datensätze in die Datenbank einzufügen, bekomme ich eine NullPointerException, obwohl ich sicher, dass Sie Werte zuweisen, um die workflow-Elemente, waren null. Hier ist meine Datenbank-Tabelle code.
Paket-Datenbank;

//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
}

Hier ist mein parser code mit der "Datensatz einfügen" - Anweisung.

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();
}

}

Kann mir bitte jemand sagen, warum das so ist, dass Sie mir die NullPointerException? Vielen Dank im Voraus!!!

Hier ist der 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)

Ja, workflow.xml vorhanden ist. Hier ist eine Kopie es unten.

<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>
  • Kannst du bitte den stacktrace posten?
  • Hier ist der stacktrace:
  • tut workflow.xml vorhanden ist ?
  • Was ist in Zeile 126? (Die Quelle gepostet wird, ist nur 123 Zeilen lang)
  • Linie 126 ist "t -.insertRecord(tempWorkflow.getAnnotationBean(), tempWorkflow.getDate(), tempWorkflow.getText(), tempWorkflow.getIdentification());"
  • Ich habe ein paar Leerzeichen gelöscht, wenn ich kopiert und eingefügt, was im Nachhinein eine sehr schlechte Idee. Tut mir Leid, dass.

InformationsquelleAutor amber4478 | 2012-12-15
Schreibe einen Kommentar