最近公司做的项目中要求把项目实施单位的原有系统中的表导入到我们公司现在的数据库中,原系统数据库与现数据库的表结构不太一样,只是把对应字段中的记录导入到现在数据库中,就写了这么一个小程序来辅助完成。

import java.sql.Connection;

/**
 * <p>Copyright: Copyright (c) 2009</p>
 * <p>Company: </p>
 * @author zfsn
 * @version 2009/11/28
 */
public class DBConvert {
	
	//原表数据库驱动及密码
	 String fdriverClassName = "net.sourceforge.jtds.jdbc.Driver";
	 String fjdbcurl = "jdbc:jtds:sqlserver://localhost:1433/OA1";
	 String fdbuser ="sa";
	 String fdbpassword ="";
	
	//目标表数据库驱动及代码
	 String tdriverClassName = "net.sourceforge.jtds.jdbc.Driver";
	 String tjdbcurl = "jdbc:jtds:sqlserver://localhost:1433/OA";
	 String tdbuser ="sa";
     String tdbpassword ="";
	
    //ftable原数据库表名,fcolumn原表对应字段
	//ttable目标数据库表名,tcolumn目标表对应字段
	//dir生成xml存放路径,xmlFile生成的xml名称
	String ftable[]={"jhbj_gov_acceptdocument","jhbj_gov_accepttype"};
	String ttable[]={"oaxietong_GSXX","oaxietong_GSLB"};
	String fcolumn[][]={{"acceptD_id","acceptD_bh","acceptD_zh","acceptD_bt","acceptD_bm","acceptD_sj","acceptD_ztc","acceptT_id"},{"acceptT_id","acceptT_name","acceptT_describe","Del_Flag"}};
	String tcolumn[][]={{"GWID","GWWH","GWRY","GWBT","GWZS","GWSJ","GWZY","GWLB"},{"LBID","LBMC","LBSM","LBBJ"}};
	String dir="c:/";
	String xmlFile[]={"jhbj_gov_acceptdocument.xml","jhbj_gov_accepttype.xml"};
     
	
	//生成的xml文件
	public void DBToXml(){
		
		MDBToXML dbToXml=new MDBToXML();
		try {
			Connection conn=dbToXml.getConn(fdriverClassName, fjdbcurl, fdbuser, fdbpassword);
			dbToXml.BuildXMLDoc(conn, ftable, dir);
		} catch (Exception e) {
			System.out.println("表导出失败,请与管理员联系");
			e.printStackTrace();
		}
		
	}
	
	//将xml的内容导入到目标表中
	public void XmlToDB(){
		MXMLToDB mXmlToDB=new MXMLToDB();
		
		try {
			Connection conn=mXmlToDB.getConn(tdriverClassName, tjdbcurl, tdbuser, tdbpassword);
			mXmlToDB.ParseXMl(conn, ftable, ttable, fcolumn, tcolumn, dir, xmlFile);
		} catch (Exception e) {
			System.out.println("表插入失败,请与管理员联系");
			e.printStackTrace();
		}
		
	}
	
	/*执行表导入之前一定要取消目标表的主键及标识(为否),并将目标表的外键关系取消
	执行结束后恢复主键、标识、外键关系
	导出表与导入表列数与类型必须一致
	导出表生成的xml以导出表对应的名字命名
	将被导入数据库表中对应字段的长度设为足够大,以便容纳下将要导入的数据*/
	public static void main(String[] args){
		
		DBConvert dbConvert=new DBConvert();
		
		//表导出
		dbConvert.DBToXml();
		
		//表导入
		dbConvert.XmlToDB();
		
	}
	
}

 

import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

/**
 * <p>Copyright: Copyright (c) 2009</p>
 * <p>Company: </p>
 * @author zfsn
 * @version 2009/11/28
 */
public class MDBToXML {
	
		 public void BuildXMLDoc(Connection conn,String tables[],String dir)throws Exception{
			       
					 for(int i=0;i<tables.length;i++){
						
						 //创建根节点以表的名字为根节点
						 Element rootElement = new Element("dbData");
						 //根节点添加到文档中
						  Document myDocument = new Document(rootElement);
						  //将表中的内容查处放到resultset
						ResultSet resultset= selectTable(conn,tables[i]);
						ResultSetMetaData rsmd=resultset.getMetaData();
						//获得表中所包含的列数
						int numCols = rsmd.getColumnCount();
						//System.out.println("db_to_xml:numCols:" + numCols);
						 //每个表都清零一次以便统计每个表有多少个元素
						  int j=1;
						while (resultset.next()) {
							//以表名为元素名,并且为每个元素设置number编号
								Element elements=new Element(tables[i]);
								elements.setAttribute("number",""+j++);
								//遍历每一列,并取得元素值
								for (int k=1; k <= numCols; k++) {
									String colval=resultset.getString(k);
									//如果没有元素设置为空字符串
									if(resultset.wasNull()){
										colval=" ";
									    }
									//将表中每一个字段的名和值添加到元素中
								     elements.addContent(new Element(rsmd.getColumnName(k)).setText("\'"+colval+"\'"));
							         }
							rootElement.addContent(elements);
						}
						 //将doc写到指定的xml中
						XMLOutputter XMLOut=new XMLOutputter(Format.getPrettyFormat());
						XMLOut.output(myDocument, new FileOutputStream(dir+tables[i]+".xml"));
					
				 }
System.out.println("数据库中的表导出成功!!导出位置为"+dir);					
		 }
	
		 public  Connection getConn(String fdriverClassName,String fjdbcurl,String fdbuser,String fdbpassword)throws Exception{
			 Class.forName(fdriverClassName);
			 Connection conn=DriverManager.getConnection(fjdbcurl,fdbuser,fdbpassword);
			 return conn;
		
		 }
		public  ResultSet selectTable(Connection conn,String tableName)throws Exception{
			Statement stat=conn.createStatement();
			String sql="select *from " +tableName;
			ResultSet rs=stat.executeQuery(sql);
			return rs;
		}
	
}

 

import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

/**
 * <p>Copyright: Copyright (c) 2009</p>
 * <p>Company: </p>
 * @author zfsn
 * @version 2009/11/28
 */
public class MXMLToDB {
	 
	@SuppressWarnings("unchecked")
	public void ParseXMl(Connection conn,String ftable[],String ttable[],String fcolumn[][],String tcolumn[][],String dir,String xmlFile[]) throws Exception {
		
		//判断输入的原表跟目标表的长度和原表字段与目标表的字段是否一样长
		if(isEquals(ftable, ttable)==true)
		{
			for(int j=0;j<fcolumn.length;j++){
				if(fcolumn[j].length!=tcolumn[j].length){
					System.out.println("输入的原表跟目标表的长度不一样或者原表字段与目标表的字段不一样!");
					return;
				}
			}
		}else{
			System.out.println("输入的原表跟目标表的长度不一样或者原表字段与目标表的字段不一样!");
			return;
		}
		
		//删除原表中的内容
	for(int j=0;j<ttable.length;j++){
			String tableName=ttable[j];
			String sql="delete from "+ tableName;
			executeTable(conn,sql);
System.out.println("原表中的数据删除成!!!");			
		}
	
	SAXBuilder sb = new SAXBuilder();// 建立构造器
for(int xx=0;xx<xmlFile.length;xx++){
	Document doc = sb.build(new FileInputStream(dir+xmlFile[xx]));// 读入指定文件
	Element root = doc.getRootElement();// 获得根节点
	List list = root.getChildren();// 将根节点下的所有子节点放入List中	
		for (int i = 0; i < list.size(); i++) {
			Element item = (Element) list.get(i);// 获取节点实例
			//String tableName = item.getName();// 获得元素节点的值为表名
			//System.out.println("-----------" + tableName);
			// 获得所有的content一个[[Text:], [Element: <title/>], [Text:], [Element:
			// <content/>], [Text: ],
			// [Element: <email/>], [Text:]]
			List llist = item.getContent();
			Iterator it = llist.iterator();
			// 获取表中每一个字段的值,如title,content,email,放到columnList
			List columnList = new ArrayList();
			while (it.hasNext()) {
				Object object = it.next();
				if (!object.toString().substring(1, 2).equals("T"))
					columnList.add(object.toString().substring(
							object.toString().indexOf("<") + 1,
							object.toString().indexOf("/")));
				else {
					continue;
				}
			}

			Map columndata = new HashMap();// 存储表字段与对应的值
			Iterator column = columnList.iterator();
			while (column.hasNext()) {
				// System.out.println(column.next());
				String columnname = column.next().toString();
				String value = item.getChild(columnname).getText();// 取得属性值
				
			//将xml中的字段拿出来与给定原表的字段比较,如果相等转换为目标表的字段并存储到map中	
				for(int k=0;k<fcolumn[xx].length;k++){
					if(columnname.equals(fcolumn[xx][k])){
						
							 columndata.put(tcolumn[xx][k], value);
//System.out.println(tcolumn[xx][k]+"-->"+ value);	
							 
					}
				}
			}
			
			
        //拼sql语句
			String aa = "", bb = "";
			int m = 0;
			//遍历map中的key,value组成表中的一行
			Set<Map.Entry> set = columndata.entrySet();
			for (Map.Entry me : set) {
				if("id".equals(me.getKey()))continue;
				else{
						String key = (String) me.getKey();
						String value = (String) me.getValue();
						if (m != 0) {
							aa = aa + "," + key;
							bb = bb + "," + value;
						} else {
							aa = key;
							bb = value;
						}
						m++;
				}
				
			}
			
			 if(!"".equals(aa)&&!"".equals(bb)){		
					String sql = "insert into " + ttable[xx] + "(" + aa + ") values ("
								+ bb + ")";
System.out.println(sql);
			executeTable(conn,sql);
				}//if
		}
  }//for xx
System.out.println("祝贺你导入成功!!!");
}
	
	public static void executeTable(Connection conn,String sql)throws Exception{
		Statement stat=conn.createStatement();
		stat.execute(sql);
	}
	
	 public  Connection getConn(String fdriverClassName,String tjdbcurl,String tdbuser,String tdbpassword)throws Exception{
		 Class.forName(fdriverClassName);
		 Connection conn=DriverManager.getConnection(tjdbcurl,tdbuser,tdbpassword);
		 return conn;
	
	 }

	 public static boolean isEquals(String fSource[],String tSource[] ){
		 
		return(fSource.length==tSource.length?true:false);	
		 
	 }

}