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();
}
}
}
将XML文件写入数据库中
最新推荐文章于 2024-07-16 13:37:08 发布