Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package my.jdbc.app;
- import java.sql.SQLException;
- import org.xml.sax.Attributes;
- import org.xml.sax.SAXException;
- import org.xml.sax.helpers.DefaultHandler;
- public class MyEventHandler extends DefaultHandler {
- final MyConnectionHandler connection;
- int orderNo;
- String name;
- boolean isItem = false;
- public MyEventHandler() throws SQLException {
- // Setup a database connection
- connection = new MyConnectionHandler();
- }
- @Override
- public void startDocument() throws SAXException {
- try {
- // Clear all previous entries out of the database table to avoid primary key conflicts
- connection.clear();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- @Override
- public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
- // Check if current element is an <item>
- if(qName == "item") {
- // If so, switch to item mode by setting the boolean isItem to true
- isItem = true;
- // Getting the "orderNo" attribute and parsing it to Integer
- orderNo = Integer.parseInt(attributes.getValue("orderNo"));
- }
- }
- @Override
- public void endElement(String uri, String localName, String qName) throws SAXException {
- // If the program is in "item mode" - and therefore the necessary elements have been gathered - shoot an insert statement
- if(isItem) {
- try {
- //
- connection.insertItem(orderNo, name);
- } catch (NumberFormatException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- // Reset the isItem boolean
- isItem = false;
- }
- @Override
- public void characters(char[] ch, int start, int length) throws SAXException {
- // If element is an item, save the item's textual content
- if(isItem) {
- name = new String(ch, start, length);
- }
- }
- @Override
- public void endDocument() throws SAXException {
- try {
- // Close the database connection to avoid socket leaks
- connection.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement