gpt4 book ai didi

java - 如何将多个xml数据存储到java数据库中

转载 作者:行者123 更新时间:2023-11-30 00:24:38 25 4
gpt4 key购买 nike

我将 xml 存储在 java 数据库中。在java xml中成功检索,但在我的sql中我无法以某种方式存储它。数据未插入mysql。

   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中。那么我的代码有什么问题吗?

最佳答案

您可以在 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;
}

关于java - 如何将多个xml数据存储到java数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22979602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com