Advertisement
coderbot

XML to SQLite Data Import

May 30th, 2014
499
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 12.86 KB | None | 0 0
  1. /*
  2.     XML to SQLite import.
  3.     Application Program.
  4.  
  5. Author: Jatin Thakur
  6.         coderbots.blogspot.com
  7.  
  8.         30/5/14
  9. */
  10.  
  11.  
  12. import java.io.BufferedReader;
  13. import java.io.File;
  14. import java.io.IOException;
  15. import java.io.InputStreamReader;
  16. import java.sql.*;
  17. import java.util.logging.Level;
  18. import java.util.logging.Logger;
  19. import java.util.regex.Matcher;
  20. import java.util.regex.Pattern;
  21. import javax.xml.parsers.DocumentBuilder;
  22. import javax.xml.parsers.DocumentBuilderFactory;
  23. import javax.xml.parsers.ParserConfigurationException;
  24. import org.w3c.dom.Document;
  25. import org.w3c.dom.NodeList;
  26. import org.xml.sax.SAXException;
  27.  
  28. public class CRUD {
  29.  
  30.     public static final String driver = "org.sqlite.JDBC";
  31.     static Statement stmt;
  32.     static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  33.     static String tableName = "MyContacts";
  34.    
  35.     //READ
  36.     public static void readContact(){
  37.         System.out.println("\nEnter the Contact Name to query: ");
  38.         String name = null;
  39.         try {
  40.             name = br.readLine();
  41.         } catch (IOException ex) {
  42.             System.out.println("Could not read input");
  43.         }
  44.         try{
  45.             ResultSet res = stmt.executeQuery("SELECT * FROM "+tableName+" WHERE Name = '"+name+"';");
  46.             displayResult(res);
  47.         }catch(SQLException e){
  48.             System.out.println("Error reading contact information "+e.toString());
  49.         }    
  50.     }
  51.    
  52.    
  53.     //UPDATE
  54.    
  55.     public static void addContact(){
  56.        
  57.         String name = null, address = null, phoneNo = null;
  58.         int age = 0;
  59.         try {
  60.             System.out.println("\nContact's Name: ");
  61.             name = br.readLine();
  62.             System.out.println("\nAge: ");
  63.             age = Integer.parseInt(br.readLine());
  64.             System.out.println("\nAddress: ");
  65.             address = br.readLine();
  66.             System.out.println("\nPhone: ");
  67.             phoneNo = br.readLine();
  68.         } catch (IOException ex) {
  69.             Logger.getLogger(CRUD.class.getName()).log(Level.SEVERE, null, ex);
  70.         }
  71.         try{
  72.             //if age=0 insert null instead and not 0
  73.             if(age==0){stmt.execute("INSERT INTO "+tableName+" (Name, Address, PhoneNo) VALUES ('"+name+"', '"+address+"', '"+phoneNo+"');");}
  74.             else
  75.             stmt.execute("INSERT INTO "+tableName+" (Name, Age, Address, PhoneNo) VALUES ('"+name+"', "+age+", '"+address+"', '"+phoneNo+"');");
  76.         }catch(SQLException e){System.out.println("Error while adding Contact"+e.toString());}
  77.     }
  78.    
  79.     public static void modifyContact(){
  80.         System.out.println("\nEnter the Contact's Name: ");
  81.         String name = null;
  82.         try {
  83.             name = br.readLine();
  84.         } catch (IOException ex) {
  85.             Logger.getLogger(CRUD.class.getName()).log(Level.SEVERE, null, ex);
  86.         }
  87.         ResultSet res=null;
  88.         try {
  89.             res = stmt.executeQuery("SELECT * FROM "+tableName+" WHERE Name = '"+name+"';");
  90.         } catch (SQLException ex) {
  91.             Logger.getLogger(CRUD.class.getName()).log(Level.SEVERE, null, ex);
  92.         }
  93.        
  94.         try {
  95.             int count=0;
  96.             while(res.next()){count++;}
  97.            
  98.            
  99.         if(count>0){
  100.                 res = stmt.executeQuery("SELECT * FROM "+tableName+" WHERE Name = '"+name+"';");
  101.                 System.out.println("Results found: ");
  102.                 displayResult(res);
  103.                 System.out.println("\nEnter the ID to modify: ");
  104.                 String id = br.readLine();
  105.                 System.out.println("\nColumn to modify: ");
  106.                 String col = br.readLine();
  107.                 System.out.println("\nEnter new column value: ");
  108.                 String colVal = br.readLine();
  109.                
  110.                 if(col.matches("Age")){
  111.                     int ageA = Integer.parseInt(colVal);
  112.                     if(ageA==0){stmt.executeUpdate("UPDATE "+tableName+" SET "+col+" = NULL WHERE ID = "+id+";");}
  113.                     else{
  114.                         stmt.executeUpdate("UPDATE "+tableName+" SET "+col+" = "+ageA+" WHERE ID = "+id+";");
  115.                     }
  116.                 }else{
  117.                 stmt.executeUpdate("UPDATE "+tableName+" SET "+col+" = '"+colVal+"' WHERE ID = "+id+";");
  118.                 }
  119.                 System.out.println("Contact Updated!");
  120.             }
  121.         } catch (SQLException ex) {
  122.                 Logger.getLogger(CRUD.class.getName()).log(Level.SEVERE, null, ex);
  123.             } catch (IOException ex) {
  124.                 Logger.getLogger(CRUD.class.getName()).log(Level.SEVERE, null, ex);
  125.          }  
  126.     }
  127.    
  128.     //DELETE
  129.     public static void deleteContact(){
  130.                 System.out.println("\nEnter the Contact's Name: ");
  131.         String name = null;
  132.         try {
  133.             name = br.readLine();
  134.         } catch (IOException ex) {
  135.             Logger.getLogger(CRUD.class.getName()).log(Level.SEVERE, null, ex);
  136.         }
  137.         ResultSet res=null;
  138.         try {
  139.             res = stmt.executeQuery("SELECT * FROM "+tableName+" WHERE Name = '"+name+"';");
  140.         } catch (SQLException ex) {
  141.             Logger.getLogger(CRUD.class.getName()).log(Level.SEVERE, null, ex);
  142.         }
  143.        
  144.         try {
  145.             int count=0;
  146.             while(res.next()){count++;}
  147.            
  148.             res = stmt.executeQuery("SELECT * FROM "+tableName+" WHERE Name = '"+name+"';");
  149.         if(count>0){
  150.                 System.out.println("\nResults found: ");
  151.                 displayResult(res);
  152.                 System.out.println("\nEnter the ID to delete: ");
  153.                 String id = br.readLine();
  154.                 stmt.execute("DELETE FROM "+tableName+" WHERE ID = "+id+";");
  155.                 System.out.println("Contact Deleted!");
  156.         }
  157.         } catch (SQLException ex) {
  158.             Logger.getLogger(CRUD.class.getName()).log(Level.SEVERE, null, ex);
  159.         } catch (IOException ex) {
  160.             Logger.getLogger(CRUD.class.getName()).log(Level.SEVERE, null, ex);
  161.         }
  162.     }
  163.    
  164.     public static void deleteTable() {
  165.         System.out.println("Do you want to delete the table(y/n): ");
  166.        
  167.         String input = null;
  168.         try {
  169.             input = br.readLine();
  170.         } catch (IOException ex) {
  171.             System.out.println("Could not read input");
  172.         }
  173.         if(input.equalsIgnoreCase("yes")||input.equalsIgnoreCase("y")){
  174.             try {
  175.                 stmt.execute("DROP TABLE "+tableName+" ;");
  176.             } catch (SQLException ex) {
  177.                System.out.println("Table could not be deleted");
  178.             }
  179.             System.out.println("ContactBook "+tableName+" deleted successfully");
  180.         }  
  181.     }
  182.    
  183.     //Reading XML into SQLite Database
  184.     public static void readXMLintoDatabase() throws SAXException, IOException, ParserConfigurationException, SQLException{
  185.             System.out.println("\nSpecify the XML file path to read Contacts From: ");
  186.             String path = br.readLine();
  187.             System.out.println("\nImporting Contacts...");
  188.             Pattern p = Pattern.compile(".*\\.xml$");
  189.             Matcher m = p.matcher(path);
  190.             if(!m.find()){
  191.                 path+=".xml";
  192.             }
  193.            
  194.             String xmlDocPath = path;
  195.             DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  196.             DocumentBuilder db = dbf.newDocumentBuilder();
  197.             Document doc = db.parse(new File(xmlDocPath));
  198.            
  199.             NodeList nameList, ageList, addressList, phoneNumberList;
  200.             try{
  201.                 nameList = doc.getElementsByTagName("Name");
  202.                 ageList  = doc.getElementsByTagName("Age");
  203.                 addressList = doc.getElementsByTagName("Address");
  204.                 phoneNumberList = doc.getElementsByTagName("PhoneNo");  
  205.             }catch(Exception e){
  206.                 System.out.println("Error reading Input XML");
  207.                 return;
  208.             }
  209.            
  210.             for(int i =0;i<nameList.getLength();++i){
  211.             String name = nameList.item(i).getFirstChild().getNodeValue();
  212.             int age = Integer.parseInt(ageList.item(i).getFirstChild().getNodeValue());
  213.             String address = addressList.item(i).getFirstChild().getNodeValue();
  214.             String phoneNumber = phoneNumberList.item(i).getFirstChild().getNodeValue();
  215.            
  216.            
  217.             try{
  218.             stmt.execute("INSERT INTO "+tableName+" (Name, Age, Address, PhoneNo) VALUES ('"+name+"', "+age+", '"+
  219.                     address+"', '"+phoneNumber+"')");
  220.             }catch(SQLException e){
  221.                 System.out.println("Skipping Duplicate...");
  222.             }
  223.          }
  224.     }
  225.  
  226.     //Display Results
  227.     public static void displayResult(ResultSet res) {
  228.        
  229.         try{
  230.         if(res==null){
  231.             res = stmt.executeQuery("SELECT * FROM "+tableName+";");
  232.         }
  233.        
  234.         System.out.println("\nID  |  Name |  Age  |  Address  |  PhoneNo");
  235.        
  236.         while(res.next()){
  237.             String id=res.getString("id");
  238.             String name = res.getString("Name");
  239.             int age=res.getInt("Age");
  240.             String Address = res.getString("Address");
  241.             String PhoneNumber = res.getString("PhoneNo");
  242.             System.out.println(id+"\t"+name+"\t"+age+"\t"+Address+"\t"+PhoneNumber);
  243.         }
  244.         }catch(SQLException e){
  245.             System.out.println("Error while fetching data: "+e.toString());}
  246.     }
  247.    
  248.     public static void main(String[] args) throws SQLException{
  249.         try{
  250.             Driver d = (Driver)Class.forName(driver).newInstance();
  251.             DriverManager.registerDriver(d);
  252.         }catch(Exception e){
  253.             System.out.println("Error loading Database Driver: "+e.toString());
  254.         }
  255.        
  256.         Connection con = null;
  257.         try{
  258.             System.out.println("---XML to SQLite---");
  259.             System.out.println("\nEnter database file URL: ");
  260.             String path = null;
  261.             try{path=br.readLine();}catch(IOException e){System.out.println("Error reading Input");}
  262.            
  263.             //In case user doesn't add .db extension to the filename
  264.             Pattern p = Pattern.compile(".*\\.db$");
  265.             Matcher m = p.matcher(path);
  266.             if(!m.find()){
  267.                 path+=".db";
  268.             }
  269.             String url="jdbc:sqlite:/"+path;
  270.             con = DriverManager.getConnection(url);
  271.         }catch (SQLException e) {                                    
  272.             System.out.println("Error creating connection: " + e.toString());
  273.         }
  274.      
  275.         stmt = con.createStatement();
  276.         String instruction;
  277.        
  278.         stmt.execute("CREATE TABLE IF NOT EXISTS "+tableName+"("
  279.                 + "ID INTEGER PRIMARY KEY AUTOINCREMENT,"
  280.                 + "Name TEXT,"
  281.                 + "Age INT,"
  282.                 + "Address TEXT,"
  283.                 + "PhoneNo TEXT UNIQUE"
  284.                 + ");");
  285.        
  286.         //Read XML File
  287.         try{
  288.         readXMLintoDatabase();
  289.         System.out.println("\nContacts Added Successfully!");
  290.         }catch(IOException | ParserConfigurationException | SAXException e){}
  291.        
  292.        
  293.         boolean more = true;
  294.         while(more){
  295.            
  296.         System.out.println("\nChoose an operation to perform on table "+tableName+": [\"quit\"] to exit");
  297.         System.out.println("1. Add Contact");
  298.         System.out.println("2. Read Contact");
  299.         System.out.println("3. Modify Contact");
  300.         System.out.println("4. Delete Contact");
  301.         System.out.println("5. View Phonebook Contents");
  302.         System.out.println("6. Delete Phonebook");
  303.        
  304.         int choice = -1;
  305.         String choiceUser = "";
  306.         try{choiceUser = br.readLine(); if(choiceUser.equalsIgnoreCase("exit")||choiceUser.equalsIgnoreCase("quit")) {return;}
  307.         else{choice = Integer.parseInt(choiceUser);}
  308.            
  309.         }catch(IOException e){System.out.println("Error reading user's choice!");}
  310.        
  311.         try{
  312.         switch(choice){
  313.             case 1: addContact();displayResult(null);System.out.println("\nPress any key to continue...");br.readLine();break;
  314.             case 2: readContact();System.out.println("\nPress any key to continue...");br.readLine();break;
  315.             case 3: modifyContact();displayResult(null);System.out.println("\nPress any key to continue...");br.readLine();break;
  316.             case 4: deleteContact();displayResult(null);System.out.println("\nPress any key to continue...");br.readLine();break;
  317.             case 5: displayResult(null);System.out.println("\nPress any key to continue...");br.readLine();break;
  318.             case 6: deleteTable();return;
  319.             default: System.out.println("\nInvalid operation selected!");
  320.         }
  321.         }catch(Exception e){}
  322.     }
  323.   }
  324. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement