将XML文件写入数据库中

来源:互联网 发布:高中英语语法视频 知乎 编辑:程序博客网 时间:2024/05/22 01:41
package edu.tsinghua.jdbc;import java.sql.*;import javax.xml.parsers.*;import org.w3c.dom.*;import java.io.*;/** * 将xml文件中的数据读取后保存到数据库中 * @author admin * */public class XMLtoDB {  static Connection con;   static String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";   static String url ="jdbc:sqlserver://localhost:1433;DatabaseName=mytest";   static String user = "xyn";   static String password = "xyn";        public static void main(String args[]){   Document doc;  // int id,age;   String name,pwd,address,age,id;   String sql = "insert into Student(name,password,address,age) values(?,?,?,?)";   try{   //连接数据库,并且得到数据库中的数据,放在结果集中   Class.forName(driver);   con = DriverManager.getConnection(url, user ,password);   PreparedStatement ps = con.prepareStatement(sql);         //创建document实例对象   DocumentBuilderFactory bf = DocumentBuilderFactory.newInstance();   DocumentBuilder db = bf.newDocumentBuilder();   doc = db.parse(new FileInputStream(new File("class2.xml")));      NodeList nlist = doc.getElementsByTagName("student");   for(int i=0;i<nlist.getLength();i++){   Element node = (Element)nlist.item(i);   //此处Student表中的id是自动生成的,所以此处的id用不上//   id = node.getAttributes().getNamedItem("id").getNodeValue();   name =node.getElementsByTagName("name").item(i).getFirstChild().getNodeValue();   pwd = node.getElementsByTagName("password").item(i).getFirstChild().getNodeValue();   address = node.getElementsByTagName("address").item(i).getFirstChild().getNodeValue();   age = node.getElementsByTagName("age").item(i).getFirstChild().getNodeValue();         ps.setString(1,name.trim());   ps.setString(2, pwd.trim());   ps.setString(3, address.trim());   ps.setInt(4, Integer.parseInt(age.trim()));   ps.executeUpdate();   }      //关闭所有的连接   if(ps!=null){   ps.close();   con.close();   }        }catch(Exception e){   e.printStackTrace();   }   }}

0 0
原创粉丝点击