2014-04-10 102 views
0

我在java數據庫中存儲xml。在Java XML中檢索成功,但在我的SQL我不能以某種方式存儲它。數據沒有被插入到mysql中。如何將多個xml數據存儲到java數據庫

public static void main (String argv []) throws SQLException{ 
     try { 
     DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); 
     DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); 
     Document doc = docBuilder.parse (new File("C:/Users/GbsIndia1/Desktop/appsettings.xml")); 

     // normalize text representation 
     doc.getDocumentElement().normalize(); 
     System.out.println ("Root element of the doc is " + 
      doc.getDocumentElement().getNodeName()); 

     NodeList listOfPersons = doc.getElementsByTagName("Name"); 
     int totalPersons = listOfPersons.getLength(); 
     System.out.println("Total no of Device : " + totalPersons); 

     for(int s=0; s<listOfPersons.getLength() ; s++){ 
      Node firstPersonNode = listOfPersons.item(s); 
      if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){ 

       Element firstPersonElement = (Element)firstPersonNode; 

       //------- 
       NodeList firstNameList = doc.getElementsByTagName("Name"); 

       Element firstNameElement = (Element)firstNameList.item(s); 

       NodeList textFNList = firstNameElement.getChildNodes(); 
       System.out.println("Hardware Name is " + 
         ((Node)textFNList.item(0)).getNodeValue().trim()); 
      } 
     } 

     Class.forName("com.mysql.jdbc.Driver"); 

    }catch (SAXParseException err) { 
    System.out.println ("** Parsing error" + ", line " 
     + err.getLineNumber() + ", uri " + err.getSystemId()); 
    System.out.println(" " + err.getMessage()); 

    }catch (SAXException e) { 
     Exception x = e.getException(); 
     ((x == null) ? e : x).printStackTrace(); 

    }catch (Throwable t) { 
     t.printStackTrace(); 
    } 
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test1" ,"root",""); 

Statement st=con.createStatement(); 

int i=st.executeUpdate("insert into test1(name) values('"+Name+"')"); 

在名稱XML標記有像

<Category> 
<Name>ABC</Name> 
<Name>DEF</Name> 
<Name>GHI</Name> 
</Category> 

我想這個數據存儲在MySQL的多個值。那麼,我的代碼有什麼問題?

+0

什麼IST'Name'在'INT I = st.executeUpdate(「插入TEST1(名稱)VALUES(」 「+姓名+」')「);'? – drkunibar

回答

0

您可以在ArrayList添加所需的值,並遍歷它來執行更新:

ArrayList<String> list = new ArrayList<String>(); 
    list.add("ABC"); 
    list.add("DEF"); 
    list.add("GHI"); 

    boolean flag = false; 
    for (int i = 0; i < list.size() && !flag; i++) { 
     checkReturnValue = st.executeUpdate("insert into test1(name) values('"+ value+"')"); 
     if(checkReturnValue < 1) 
      flag = true; 
    } 
相關問題