在Web编程过程中,往往涉及到读取XML配置文件,上网查了许多,都是通过用DOM解析或者SAX解析来完成的。下面就将我在项目中(我用的是Jdom操作XML,这里需要先下载jdom.jar包,然后将Oracle中的数据读取添加到SQL2005中,我是用jdbc读取Oracle,然后用LinkSQLServerBean.java写入SQL2005)做的关于XML解析的代码说明如下:

 

1.新件一个jdbc.xml文件,把它放到WEB-INF目录下,代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<jdbcdriver>
 <drivername>oracle.jdbc.driver.OracleDriver</drivername>
 <url>jdbc:oracle:thin:@192.168.0.25:1521:test</url>
 <username>test</username>
 <password>123</password>
</jdbcdriver>

 

2.新建一个读取jdbc.xml类,名叫ReadWebinfoJdbcXml.java,我是放到util包下,代码如下:

import java.io.File;
import java.util.ArrayList;
import java.util.List;import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;public class ReadWebinfoJdbcXml{
 //根据当前的类,得到webinfo的路径
 public String getWebinfoAddress(){
    Class theClass = ReadWebinfoJdbcXml.class;
    java.net.URL u = theClass.getResource("");
    //str会得到这个函数所在类的路径
    String str = u.toString();
    //截去一些前面6个无用的字符
    str = str.substring(6, str.length());
    //将%20换成空格(如果文件夹的名称带有空格的话,会在取得的字符串上变成%20)
    str = str.replaceAll("%20", " ");
    //查找“WEB-INF”在该字符串的位置
    int num = str.indexOf("WEB-INF");
    //截取即可
    str = str.substring(0, num + "WEB-INF".length());    //str输出为:D:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\rtes\WEB-INF
    return str;
 }
 
 public  List<String> getNodeValue(){
  SAXBuilder builder = new SAXBuilder();
  List<String> list = new ArrayList<String>();
   Document doc = null;
   try{
     doc = builder.build(new File(getWebinfoAddress()+"\\jdbc.xml"));
   }catch (Exception e){
    e.printStackTrace();
   }
   Element el = doc.getRootElement();
   List<Element> subMenuList = el.getChildren();
   for(int i=0;i<subMenuList.size();i++){
   String str = ((Element)subMenuList.get(i)).getText();
   list.add(str);
   }
   return list;
  }
 
}

3.新建一个JdbcUtil.java类,用来连接数据库,该类也在util包下,代码如下:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;import com.xtlh.rtes.util.ReadWebinfoJdbcXml;
/**
 * <!-- SQL2005驱动程序 -->
 *<jdbcdriver>
 * <drivername>com.microsoft.sqlserver.jdbc.SQLServerDriver</drivername>
 * <url>jdbc:sqlserver://192.168.0.47:1433;DataBaseName=rtes</url>
 * <username>sa</username>
 * <password>xtlh</password>
 *</jdbcdriver>
 * 
 */public class JdbcUtil{
 static ReadWebinfoJdbcXml readXml=new ReadWebinfoJdbcXml();
 static List<String> list=readXml.getNodeValue();
 static String driverName=list.get(0);
 static String url=list.get(1);
 static String username=list.get(2);
    static String password=list.get(3);
 // 1.加载驱动一次
 static{
  try{
   //Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
   Class.forName(driverName);
  } catch (ClassNotFoundException e){
   e.printStackTrace();
  }
 }
// 2.获得连接
 public static Connection getConnection(){
  Connection con = null;
//  String url="jdbc:sqlserver://192.168.0.47:1433;DataBaseName=rtes"; 
//  String username="sa";
//  String password="xtlh";
  try{
   con = DriverManager.getConnection(url,username,password);
  } catch (Exception e){
   e.printStackTrace();
  }
  return con;
 } // 3.释放资源
 public static void release(ResultSet rs, Statement stmt, Connection con){
  if (rs != null){
   try{
    rs.close();
   } catch (SQLException e){
    e.printStackTrace();
   }
  }
  if (stmt != null){
   try{
    stmt.close();
   } catch (SQLException e){
    e.printStackTrace();
   }
  }
  if (con != null){
   try{
    con.close();
   } catch (SQLException e){
    e.printStackTrace();
   }
  }
 } // 4.释放资源
 public static void release(Object obj){
  if (obj instanceof ResultSet){
   try{
    ((ResultSet) obj).close();
   } catch (SQLException e){
    e.printStackTrace();
   }
  } else if (obj instanceof Statement){
   try{
    ((Statement) obj).close();
   } catch (SQLException e){
    e.printStackTrace();
   }
  } else if (obj instanceof Connection){
   try{
    ((Connection) obj).close();
   } catch (SQLException e){
    e.printStackTrace();
   }
  }
 } // 5.打印结果集
 public static void printRS(ResultSet rs){
  if (rs == null)
   return;
  try{
   ResultSetMetaData md = rs.getMetaData();
   int colnum = md.getColumnCount();
   StringBuffer sb = new StringBuffer();
   while (rs.next()){
    for (int i = 1; i <= colnum; i++){
     sb.append(md.getColumnName(i));
     sb.append("=" + rs.getString(i) + "  ");
    }
    sb.append("\n");
   }
   System.out.println(sb.toString());
  } catch (Exception e){
   e.printStackTrace();
  }
 }
}



4.具体的实现类为ChannelJdbcImpl.java,代码如下:

 

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;import com.xtlh.rtes.database.LinkSQLServerBean;
import com.xtlh.rtes.entity.Channel;
import com.xtlh.rtes.util.JdbcUtil;
import com.xtlh.rtes.util.ToolUnit;public class ChannelJdbcImpl
{
 private Connection con= null;
 private PreparedStatement   ps= null;
 private ResultSet rs= null;
 
   /**
    * 
    * @功能描述  根据对方服务器上的channel表同步本地数据库上的channel表
    * @输入参数  无
    * @反馈值 Boolean型变量
    */
 public Boolean SynchronousChannel()
 {
  //先删除本地新路段表里的所有数据
  deleteAllChannel();
  ToolUnit tu = new ToolUnit();
  List<Channel> list=new ArrayList<Channel>();
  try{
      con = JdbcUtil.getConnection();
      String sql =  "select * from channel";
   ps = con.prepareStatement(sql);
   ps.execute();
   rs = ps.getResultSet();
   int count=1;
   while(rs.next())
   {
    Channel channel = makeEntity(tu);
    list.add(channel);
    if(count%5000==0){
     addChannel(list);
     list.clear();
    }
    count++;
   }
   //然后执行批处理添加新路段表数据,这些数据来自对方服务器上
   addChannel(list);
  }catch(Exception e){
   e.printStackTrace();
  }finally{
   JdbcUtil.release(rs);
  }
  return true;
 } private Channel makeEntity(ToolUnit tu) throws SQLException
 {
  Channel channel = new Channel();
  channel.setLxdm(tu.zhuanhuan(rs.getString("lxdm"),""));
  channel.setLxjc(tu.zhuanhuan(rs.getString("lxjc"),""));
  channel.setGldw_dm(tu.zhuanhuan(rs.getString("gldw_dm"),""));
  channel.setGldw(tu.zhuanhuan(rs.getString("gldw"),""));
  channel.setLdbh(tu.zhuanhuan(rs.getString("ldbh"),""));
  channel.setQdzh(tu.zhuanhuan(rs.getString("qdzh"),""));
  channel.setZdzh(tu.zhuanhuan(rs.getString("zdzh"),""));
  channel.setLc(tu.zhuanhuan(rs.getString("lc"),""));
  channel.setYhdw(tu.zhuanhuan(rs.getString("yhdw"),""));
  channel.setXzqh_dm(tu.zhuanhuan(rs.getString("xzqh_dm"),""));
  channel.setXzqh(tu.zhuanhuan(rs.getString("xzqh"),""));
  channel.setSfcgld(tu.zhuanhuan(rs.getString("sfcgld"),""));
  channel.setJsdj_dm(tu.zhuanhuan(rs.getString("jsdj_dm"),""));
  channel.setJsdj(tu.zhuanhuan(rs.getString("jsdj"),""));
  channel.setCdfl_dm(tu.zhuanhuan(rs.getString("cdfl_dm"),""));
  channel.setCdfl(tu.zhuanhuan(rs.getString("cdfl"),""));
  channel.setMclx_dm(tu.zhuanhuan(rs.getString("mclx_dm"),""));
  channel.setMclx(tu.zhuanhuan(rs.getString("mclx"),""));
  channel.setLjkd(tu.zhuanhuan(rs.getString("ljkd"),""));
  channel.setLmkd(tu.zhuanhuan(rs.getString("lmkd"),""));
  channel.setSjss(tu.zhuanhuan(rs.getString("sjss"),""));
  channel.setSjxsl(tu.zhuanhuan(rs.getString("sjxsl"),""));
  channel.setDm_dm(tu.zhuanhuan(rs.getString("dm_dm"),""));
  channel.setDm(tu.zhuanhuan(rs.getString("dm"),""));
  channel.setYhlc(tu.zhuanhuan(rs.getString("yhlc"),""));
  channel.setKlhlc(tu.zhuanhuan(rs.getString("klhlc"),""));
  channel.setYlhlc(tu.zhuanhuan(rs.getString("ylhlc"),""));
  channel.setKgrq(tu.zhuanhuan(rs.getString("kgrq"),""));
  channel.setJgrq(tu.zhuanhuan(rs.getString("jgrq"),""));
  channel.setTcrq(tu.zhuanhuan(rs.getString("tcrq"),""));
  channel.setBgrq(tu.zhuanhuan(rs.getString("bgrq"),""));
  channel.setPqxbj(tu.zhuanhuan(rs.getString("pqxbj"),""));
  channel.setZdzp(tu.zhuanhuan(rs.getString("zdzp"),""));
  return channel;
 }
 
 /**
  * 
  * @功能描述  添加新路段数据
  * @输入参数  list
  * @反馈值 无
  */
 public void addChannel(List<Channel> list){
  con = LinkSQLServerBean.getConnection();// 获取数据库连接
  String sql = "insert into channel values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
  try{
   con.setAutoCommit(false);//开始事务  
   ps = con.prepareStatement(sql);
   Iterator<Channel> it=list.iterator();
//   long start = System.currentTimeMillis(); 
   while(it.hasNext()){
    Channel channel=(Channel)it.next();
    ps.setString(1,channel.getLxdm() );
    ps.setString(2,channel.getLxjc());
    ps.setString(3,channel.getGldw_dm());
    ps.setString(4,channel.getGldw());
    ps.setString(5,channel.getLdbh());
    ps.setString(6,channel.getQdzh());
    ps.setString(7,channel.getZdzh());
    ps.setString(8,channel.getLc());
    ps.setString(9,channel.getYhdw());
    ps.setString(10,channel.getXzqh_dm());
    
    ps.setString(11,channel.getXzqh() );
    ps.setString(12,channel.getSfcgld());
    ps.setString(13,channel.getJsdj_dm());
    if("高速".equals(channel.getJsdj())){
     ps.setString(14,"高速公路");     
    }else if("一级".equals(channel.getJsdj())){
     ps.setString(14,"一级公路"); 
    }else if("二级".equals(channel.getJsdj())){
     ps.setString(14,"二级公路"); 
    }else if("三级".equals(channel.getJsdj())){
     ps.setString(14,"三级公路"); 
    }else if("四级".equals(channel.getJsdj())){
     ps.setString(14,"四级公路"); 
    }else{
     ps.setString(14,"四级公路"); 
    }
    ps.setString(15,channel.getCdfl_dm());
    ps.setString(16,channel.getCdfl());
    ps.setString(17,channel.getMclx_dm());
    if("水泥混凝土".equals(channel.getMclx())){
     ps.setString(18,"水泥路面");
    }else if("沥青混凝土".equals(channel.getMclx())){
     ps.setString(18,"沥青路面");
    }else{
     ps.setString(18,"砂石路面");
    }
    ps.setString(19,channel.getLjkd());
    ps.setString(20,channel.getLmkd());
    
    ps.setString(21,channel.getSjss() );
    ps.setString(22,channel.getSjxsl());
    ps.setString(23,channel.getDm_dm());
    ps.setString(24,channel.getDm());
    ps.setString(25,channel.getYhlc());
    ps.setString(26,channel.getKlhlc());
    ps.setString(27,channel.getYlhlc());
    ps.setString(28,channel.getKgrq());
    ps.setString(29,channel.getJgrq());
    ps.setString(30,channel.getTcrq());
    
    ps.setString(31,channel.getBgrq());
    ps.setString(32,channel.getPqxbj());
    ps.setString(33,channel.getZdzp());
    ps.addBatch(); //因为我用到的数据量比较大,所以需要批处理语句。        
   }      
//   long end = System.currentTimeMillis();   
//   System.out.println("addBatch耗时:"+(end - start)+"ms");   
   ps.executeBatch(); //   long end2 = System.currentTimeMillis();  
//   System.out.println("executeBatch耗时:"+(end2 - end)+"ms");   
   con.commit();//提交事务 
   ps.clearBatch();   }catch(RuntimeException e){   
   try{   
    con.rollback();   
      }catch (SQLException e1) {   
    e1.printStackTrace();  
      }
      e.printStackTrace();   
  }catch(Exception e){
   try{   
    con.rollback();   
   }catch(SQLException e1){   
    e1.printStackTrace();   
   }   
   e.printStackTrace();   
  }finally{
   LinkSQLServerBean.ReleaseDatabase(ps);
   LinkSQLServerBean.ReleaseDatabase(con);
  }
 }
 
 /**
  * 
  * @功能描述  删除新路段表数据
  * @输入参数  无
  * @反馈值 无
  */
 public void deleteAllChannel(){
  con = LinkSQLServerBean.getConnection();// 获取数据库连接
  String sql="delete from channel";
  try{
   con.setAutoCommit(false);//开始事务  
   ps = con.prepareStatement(sql);
   ps.execute();
   con.commit();//提交事务 
  }catch(RuntimeException e){   
   try{   
    con.rollback();   
      }catch (SQLException e1) {   
    e1.printStackTrace();  
      }
      e.printStackTrace();   
  }catch(Exception e){
   try{   
    con.rollback();   
   }catch(SQLException e1){   
    e1.printStackTrace();   
   }   
   e.printStackTrace();   
  }finally{
   LinkSQLServerBean.ReleaseDatabase(ps);
   LinkSQLServerBean.ReleaseDatabase(con);
  }
 }
 
}

5.LinkSQLServerBean.java类,也放在util包下,该类用来连接SQL2005数据库,这里用到Tomcat的连接池,代码如下:

 

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;public class LinkSQLServerBean
{
 static Context  ctx  = null;
 static DataSource ds  = null;
 static
 {
  try
  {
   ctx = new InitialContext();
   ds = (DataSource) ctx.lookup("java:/comp/env/jdbc/rtes");
  }
  catch(Exception e){ e.printStackTrace();}
 }
 /**
  * 
  * @Function getConnection()
  * @Description 获取数据库连接
  * @Return 返回数据库连接的对象,返回值类型-Connection
  */
 public static Connection getConnection()
 {
  Connection conn = null;
  try
  {
   conn = ds.getConnection();
  }
  catch(Exception e){ e.printStackTrace();}
  
  return conn;
 } /**
  * 
  * @Function     ReleaseDatabase(Object o)
  * @Description  释放数据库连接||关闭Statement||关闭PreparedStatement||关闭ResultSet
  * @Input        Connection||Statement||PreparedStatement||ResultSet
  */
 public static void ReleaseDatabase(Object o)
 {
  try
  {
   if(o instanceof ResultSet)
   {
      ((ResultSet)o).close();
   }
   else if(o instanceof Statement)
   {
      ((Statement)o).close();
   }
   else if(o instanceof PreparedStatement)
   {
      ((PreparedStatement)o).close();
   }
   else if(o instanceof Connection)
   {
      ((Connection)o).close();
   }
  }catch(Exception e)
  {
   e.printStackTrace();
  }
 }
}

 

6.连接池配置文件为:首打开tomcat下的conf文件,然后打开context.xml文件,填写如下代码:

 

<Resource name="jdbc/rtes" 
       auth="Container" 
       type="javax.sql.DataSource" 
       driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver" 
       url="jdbc:sqlserver://192.168.0.47:1433;DataBaseName=rtes" 
       username="sa" 
       password="xtlh" 
       maxIdle="10" 
       maxWait="5000" 
       maxActive="200" />

 

关闭该文件,重启Tomcat,这样就把连接池配置成功了。