将XML文件写入数据库中

8 篇文章 0 订阅
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();
		   }
	   }
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值