无法将XML解析数据导入SQL数据库表

时间:2014-07-09 14:06:57

标签: java sql xml saxparser

我有简单的XML文件(见下文)

</Students>`<?xml version="1.0" encoding="utf-8"?>
<Students>
 <Student id="1">
    <id>001</id>
    <firstName>John</firstName>
    <lastName>Smith</lastName>
</Student>
<Student id="2">
    <id>002</id>
    <firstName>Jamie</firstName>
    <lastName>Lavery</lastName>
</Student>
<Student id="3">
    <id>003</id>
    <firstName>Emma</firstName>
    <lastName>Lavery</lastName>
</Student>
</Students> 
   `> 

我正在尝试将其解析为类型学生的Arraylist然后将其插入到SQL数据库表中......下面是解析器和数据库连接的代码

Student.java

package uk.ac.qub.XML_Parser;

public class Student {
private int id;
private String firstName;
private String lastName;

public Student(){

}

public Student(int id, String firstName, String lastName) {
    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getFirstName() {
    return firstName;
   }

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

public String toString() {
    return "ID : " + this.id + "\nFirst Name : "
            + this.firstName + "\nLast Name : " + this.lastName;
}

}

XML_Handler.java

package uk.ac.qub.XML_Parser;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;



public class XML_Handler extends DefaultHandler {

//List to hold Employees object
private List<Student> studentList = null;
private Student student = null;


//getter method for employee list
public List<Student> getStudentList() {
    return studentList;
}


boolean bId = false;
boolean bFirstName = false;
boolean bLastName = false;


@Override
public void startElement(String uri, String localName, String qName, Attributes    attributes)
        throws SAXException {

    if (qName.equalsIgnoreCase("Student")) {

        String id = attributes.getValue("id");
        //initialize S object and set id attribute
        student = new Student();
        student.setId(Integer.parseInt(id));

        if (studentList == null)
            studentList = new ArrayList<>();
    } else if (qName.equalsIgnoreCase("id")) {
        //set boolean values for fields, will be used in setting  variables
        bId = true;
    } else if (qName.equalsIgnoreCase("firstName")) {
        bFirstName = true;
    } else if (qName.equalsIgnoreCase("lastName")) {
        bLastName = true;
    }

}


@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
    if (qName.equalsIgnoreCase("Student")) {
        //add Employee object to list
        studentList.add(student);
    }
}


@Override
public void characters(char ch[], int start, int length) throws SAXException {

    if (bId) {
        //age element, set age
        student.setId(Integer.parseInt(new String(ch, start, length)));
        bId = false;
    } else if (bFirstName) {
        student.setFirstName(new String(ch, start, length));
        bFirstName = false;

    } else if (bLastName) {
        student.setLastName(new String(ch, start, length));
        bLastName = false;
    }
}
}

XML_SAX_Parser.java

package uk.ac.qub.XML_Parser;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXException;





public class XML_SAX_Parser {

public void SAX_Parser() {


    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    try {
        SAXParser saxParser = saxParserFactory.newSAXParser();
        XML_Handler handler = new XML_Handler();
        saxParser.parse(new File(
    "c:/users/jamie/desktop/DISSERTATION/student.xml"),
                        handler);
        // Get Student  list
        List<Student> studentList = handler.getStudentList();

        for (Student student : studentList)
            System.out.println(student);
    } catch (ParserConfigurationException | SAXException | IOException e) {
        e.printStackTrace();
    }

  }

  }  

DBConnection.java

package uk.ac.qub.DB_Connection;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import uk.ac.qub.XML_Parser.Student;


public class DBConnection {

// this is a local host url.
private static String url = "jdbc:mysql://localhost/test1";
private static String userName = "root";
private static String password = "";

public void startDB(){
    List<Student> studentList = new ArrayList<Student>();
    connectionDriver();
    passinUpdate(studentList);



}

// Enables java to connect to mysql database
public  void connectionDriver() {
    try {
        Class.forName("com.mysql.jdbc.Driver");
        System.out.println("Connected to mySQL");
    } catch (ClassNotFoundException e) {

        e.printStackTrace();
    }
}


public  void passinUpdate(List<Student> studentList) {

    try {
        Connection connect2 = DriverManager.getConnection(url, userName,
                password);
        System.out.println("Established Conenction.....");
        String insertStudent = "INSERT INTO Student"
                + "(id, firstName, lastName) VALUES" + "('student.id','student.firstName','student.lastName')";

        PreparedStatement statement2 = connect2
                .prepareStatement(insertStudent);


        statement2.setInt(1, ((Student) studentList).getId());
        statement2.setString(2, ((Student) studentList).getFirstName());
        statement2.setString(3, ((Student) studentList).getLastName());

        statement2.execute();

    } catch (SQLException sqlException) {
        if (sqlException.getErrorCode() == 1007) {
            // Database already exists error
            System.out.println(sqlException.getMessage());
        } else {
            // Some other problems, e.g. Server down, no permission, etc
            sqlException.printStackTrace();
        }
    }
}

}

输出....

    Connected to mySQL
    Established Conenction.....
  Exception in thread "main" java.lang.ClassCastException: java.util.ArrayList cannot be cast to uk.ac.qub.XML_Parser.Student
at uk.ac.qub.DB_Connection.DBConnection.passinUpdate(DBConnection.java:61)
at uk.ac.qub.DB_Connection.DBConnection.startDB(DBConnection.java:25)
at uk.ac.qub.Start.Start_Program.main(Start_Program.java:9)

这是我所知道的很多代码,但真的不确定问题出在哪里.....感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

Java告诉您问题的确切位置:

uk.ac.qub.DB_Connection.DBConnection.passinUpdate(DBConnection.java:61)

如果方法passinUpdate的参数是

List<Student> studentList

你不能把它当作

(Student) studentList

做一个循环:

for (Student student : studentList) {
  statement2.setInt(1, student.getId());
  statement2.setString(2, student.getFirstName());
  statement2.setString(3, student.getLastName());
  statement2.execute();
}

答案 1 :(得分:0)

您的方法有几个问题

public  void passinUpdate(List<Student> studentList) {

    try {
        Connection connect2 = DriverManager.getConnection("", "",
                "");
        System.out.println("Established Conenction.....");

        //Passing parameters to query
        String insertStudent = "INSERT INTO Student" + "(id, firstName, lastName) VALUES" + "(?,?,?)";

        //Create a loop for students
        for(Student student : studentList){
            PreparedStatement statement2 = connect2 .prepareStatement(insertStudent);

            //Incorrect cast was used here
            statement2.setInt(1, student.getId());
            statement2.setString(2, student.getFirstName());
            statement2.setString(3, student.getLastName());

            statement2.execute();
        }

    } catch (SQLException sqlException) {
        if (sqlException.getErrorCode() == 1007) {
            // Database already exists error
            System.out.println(sqlException.getMessage());
        } else {
            // Some other problems, e.g. Server down, no permission, etc
            sqlException.printStackTrace();
        }
    }
}