import java.io.*;
import java.sql.*;
import org.xml.sax.*;
import javax.xml.parsers.*;
import org.xml.sax.helpers.*;
/**
* Description of the Class
*
* @author Danny Ayers
* @created 24 February 2001
*/
public class XMLToJDBC extends DefaultHandler {
String driver = "com.mysql.jdbc.Driver";
String database = "jdbc:mysql://localhost/Maturavorbereitung";
String user = "alle";
String password = "abtedv";
Connection conn = null;
private boolean root;
// private StringBuffer sql;
private String table;
public XMLToJDBC(String args[]) {
table = args[1];
try {
Class.forName(driver);
conn = DriverManager.getConnection(database, user, password);
parse(args[0]);
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void parse(String uri) {
try {
SAXParserFactory saxfactory = SAXParserFactory.newInstance();
SAXParser saxparser = saxfactory.newSAXParser();
XMLReader xmlreader = saxparser.getXMLReader();
// XMLReader xmlreader = (XMLReader)saxparser.getParser();
xmlreader.setContentHandler(this);
xmlreader.setErrorHandler(this);
xmlreader.setFeature("http://xml.org/sax/features/validation", true);
xmlreader.parse(uri);
} catch (Exception e) {
e.printStackTrace();
}
}
// DocumentHandler methods
public void startDocument() {
root = true;
System.out.println("start document");
}
public void startElement(String uri, String local, String qname, Attributes attrs) {
if (root) {
root = false;
return;
}
StringBuffer sql = new StringBuffer("INSERT INTO " + table + " (");
int nfields = attrs.getLength();
sql.append(attrs.getLocalName(0));
for (int i = 1; i < nfields; i++) {
sql.append(", " + attrs.getLocalName(i));
}
sql.append(") VALUES (");
sql.append("'" + attrs.getValue(0) + "'");
for (int i = 1; i < nfields; i++) {
sql.append(", '" + attrs.getValue(i) + "'");
}
sql.append(")");
System.out.println(sql);
executeSQL(sql.toString());
}
public void characters(char ch[], int start, int length) {
}
public void endElement(String uri, String local, String qname) {
}
public void endDocument() {
System.out.println("end document");
}
public void warning(SAXParseException e) {
System.out.println("Warning : " + e);
}
public void error(SAXParseException e) {
System.out.println("\nError : " + e);
}
public void fatalError(SAXParseException e) {
System.out.println("\n\nFatal error : " + e);
}
public void executeSQL(String sqlstring) {
try {
Statement stmt = conn.createStatement();
stmt.executeUpdate(sqlstring);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
if (args.length != 2) {
System.out.println("java XMLToJDBC [source] [table]");
System.exit(1);
}
String[] argumente = new String[2];
argumente[0] = "C:/Orte.xml";
argumente[1] = "Ort";
new XMLToJDBC(argumente);
}
}