需求:将用户从数据库导出,并且导入另一个用户后更新其中一些表的数据值。
1、XML原始文件
<?xml version="1.0" encoding="UTF-8" ?> <database> <tables> <!-- 修改BUSINESS_SYSTEM表 --> <table name = "BUSINESS_SYSTEM"> <!-- 终端管理 --> <fields id="2"> <field IP = "xxxx.xxxx.xxxx.xxxx" /> <field PORT = "40009"/> </fields> <!-- 权限管理 --> <fields id="3"> <field IP = "xxxx.xxxx.xxxx.xxxx"/> <field PORT = "40001"/> </fields> <!-- 短彩信管理平台 --> <fields id="101"> <field IP = "xxxx.xxxx.xxxx.xxxx"/> <field PORT = "40004"/> </fields> <!-- 商户管理系统 --> <fields id="121"> <field IP = "xxxx.xxxx.xxxx.xxxx"/> <field PORT = "8080"/> </fields> <!-- 基础用户管理系统 --> <fields id="141"> <field IP = "xxxx.xxxx.xxxx.xxxx"/> <field PORT = "40001"/> </fields> <!-- 电子商务后台管理系统 --> <fields id="161"> <field IP = "xxxx.xxxx.xxxx.xxxx"/> <field PORT = "40006"/> </fields> <!-- 万能遥控器管理系统 --> <fields id="201"> <field IP = "xxxx.xxxx.xxxx.xxxx"/> <field PORT = "40013"/> </fields> <!-- 预付卡支付管理系统 --> <fields id="202"> <field IP = "xxxx.xxxx.xxxx.xxxx"/> <field PORT = "40014"/> </fields> <!-- 日志管理系统 --> <fields id="242"> <field IP = "xxxx.xxxx.xxxx.xxxx"/> <field PORT = "40023"/> </fields> <!-- 业务管理系统 --> <fields id="241"> <field IP = "xxxx.xxxx.xxxx.xxxx"/> <field PORT = "40010"/> </fields> </table> <!-- 修改property_value表 --> <table name = "PROPERTY_VALUE"> <!-- 数据库URL --> <fields PROPERTY_VALUE_ID="12"> <field VALUE = "jdbc:oracle:thin:@xxxx.xxxx.xxxx.xxxx:1521:orcl"/> </fields> <!-- log日志URL --> <fields PROPERTY_VALUE_ID="38"> <field VALUE = "jdbc:oracle:thin:@xxxx.xxxx.xxxx.xxxx:1521:orcl"/> </fields> <!-- ftp配置 --> <fields PROPERTY_VALUE_ID="13"> <field VALUE = "192.168.0.112"/> </fields> <!-- 域名 --> <fields PROPERTY_VALUE_ID="45"> <field VALUE = "http://192.168.0.104/"/> </fields> <!-- jsonP --> <fields PROPERTY_VALUE_ID="74"> <field VALUE = "http://xxxx.xxxx.xxxx.xxxx:40000"/> </fields> <!-- 重定向IP --> <fields PROPERTY_VALUE_ID="5"> <field VALUE = "xxxx.xxxx.xxxx.xxxx"/> </fields> <!-- 重定向PORT --> <fields PROPERTY_VALUE_ID="6"> <field VALUE = "40000"/> </fields> </table> <!-- 修改property_value表 --> <table name = "BG_PROPERTY_VALUE"> <!-- 数据库URL --> <fields BG_PROPERTY_VALUE_ID="2"> <field VALUE = "jdbc:oracle:thin:@xxxx.xxxx.xxxx.xxxx:1521:orcl"/> </fields> <!-- 图片服务器 --> <fields BG_PROPERTY_VALUE_ID="62"> <field VALUE = "http://xxxx.xxxx.xxxx.xxxx:40018/"/> </fields> <!-- 域名 --> <fields BG_PROPERTY_VALUE_ID="64"> <field VALUE = "http://192.168.0.104:8081/dfs/ws/imgSys"/> </fields> <!-- 图片服务器 --> <fields BG_PROPERTY_VALUE_ID="65"> <field VALUE = "http://xxxx.xxxx.xxxx.xxxx:40018/"/> </fields> <!-- 业务自助管理自定义系统URL --> <fields BG_PROPERTY_VALUE_ID="69"> <field VALUE = "jdbc:oracle:thin:@xxxx.xxxx.xxxx.xxxx:1521:orcl"/> </fields> <!-- LOG数据库url --> <fields BG_PROPERTY_VALUE_ID="32"> <field VALUE = "jdbc:oracle:thin:@xxxx.xxxx.xxxx.xxxx:1521:orcl"/> </fields> </table> </tables> </database>
2、XMLConfiguration解析java代码
package com.handaer.pro.xml; import java.util.ArrayList; import java.util.List; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.XMLConfiguration; import org.apache.commons.configuration.HierarchicalConfiguration.Node; public class PaserXml { @SuppressWarnings("unchecked") public List<String> initXml() { XMLConfiguration config = new XMLConfiguration(); config.setDelimiterParsingDisabled(true); config.setFileName("config/data.xml"); try { config.load(); } catch (ConfigurationException e) { e.printStackTrace(); } Node root = config.getRoot(); List<String> sqlList = new ArrayList<String>(); if (root.hasChildren()) { List<Node> tablesNodeList = root.getChildren(); for (Node tablesNode : tablesNodeList) { List<Node> tableNodeList = tablesNode.getChildren(); for (Node tableChildNode : tableNodeList) { StringBuilder sql = new StringBuilder("UPDATE "); String tableName = (String) ((Node) tableChildNode.getAttributes().get(0)).getValue(); sql.append(tableName).append(" SET "); List<Node> fieldsNodeList = tableChildNode.getChildren(); for (Node fields : fieldsNodeList) { StringBuilder filedSb = new StringBuilder(); List<Node> fieldNodeList = fields.getChildren(); int count = 0; for (Node field : fieldNodeList) { count++; String dbFieldName = (String) ((Node) field.getAttributes().get(0)).getName(); filedSb.append(dbFieldName).append("="); String dbField = (String) ((Node) field.getAttributes().get(0)).getValue(); filedSb.append("'").append(dbField).append("'"); if (count < fieldNodeList.size()) { filedSb.append(" , "); } } String idName = (String) ((Node) fields.getAttributes().get(0)).getName(); filedSb.append(" WHERE ").append(idName).append("="); String id = (String) ((Node) fields.getAttributes().get(0)).getValue(); filedSb.append(id); int headLength = sql.length(); sql.append(filedSb); System.out.println(sql.toString()); sqlList.add(sql.toString()); sql.delete(headLength, sql.length()); filedSb.delete(0, filedSb.length()); } sql.delete(0, sql.length()); } } } return sqlList; } }
3、ORACLE执行java源码
package com.handaer.pro; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import org.apache.log4j.Logger; public class OracleHelper { private static final Logger logger = Logger.getLogger(OracleHelper.class); private static int CMD_TYPE_IDX = 2; private static int CMD_ORACLE_IDX = 3; private static int CMD_FILE_PATH_IDX = 5; private static int CMD_OWNER_IDX = 7; private static int CMD_TOUSER_IDX = 9; private final String[] cmdExpArray = { "cmd", "/c", "", "", "file=", "", "owner=", "" }; private final String[] cmdImpArray = { "cmd", "/c", "", "", "file=", "", "fromuser=", "", "touser=", "" }; public void setOracleType(String type) { cmdExpArray[CMD_TYPE_IDX] = type; cmdImpArray[CMD_TYPE_IDX] = type; } public void setOracleInstance(String oracleInstance) { cmdExpArray[CMD_ORACLE_IDX] = oracleInstance; cmdImpArray[CMD_ORACLE_IDX] = oracleInstance; } public void setFilePath(String filePath) { cmdExpArray[CMD_FILE_PATH_IDX] = filePath; cmdImpArray[CMD_FILE_PATH_IDX] = filePath; } public void setOwner(String owner) { cmdExpArray[CMD_OWNER_IDX] = owner; } public void setUser(String fromUser, String toUser) { cmdImpArray[CMD_OWNER_IDX] = fromUser; cmdImpArray[CMD_TOUSER_IDX] = toUser; } public boolean preform(int type) { boolean result = false; try { if (logger.isDebugEnabled()) { logger.debug("ORACLE command : " + this); } Process ldrTmp = null; if (type == 1) { ldrTmp = Runtime.getRuntime().exec(cmdExpArray); } if (type == 2) { ldrTmp = Runtime.getRuntime().exec(cmdImpArray); } final Process ldr = ldrTmp; new Thread() { public void run() { BufferedReader reader = new BufferedReader(new InputStreamReader(ldr.getErrorStream())); try { String line = reader.readLine(); if (logger.isDebugEnabled()) { logger.debug("ORACLE Error Message:"); } while (line != null) { line = reader.readLine(); if (logger.isDebugEnabled()) { logger.debug(line); } } } catch (IOException e) { logger.error("ORACLE get error stream failed.", e); } finally { try { if (reader != null) { reader.close(); reader = null; } } catch (IOException e) { logger.error(e.getMessage(), e); } } } }.start(); new Thread() { public void run() { BufferedReader reader = new BufferedReader(new InputStreamReader(ldr.getInputStream())); try { String line = reader.readLine(); if (logger.isDebugEnabled()) { logger.debug("ORACLE Output Message: "); } while (line != null) { line = reader.readLine(); if (logger.isDebugEnabled()) { logger.debug(line); } } } catch (IOException e) { logger.error("ORACLE get input stream failed.", e); } finally { try { if (reader != null) { reader.close(); reader = null; } } catch (IOException e) { logger.error(e.getMessage(), e); } } } }.start(); try { int exitValue = ldr.waitFor(); if (exitValue == 2 || exitValue == 0) { if (logger.isDebugEnabled()) { logger.debug("ORACLE success."); } result = true; } else { logger.error("ORACLE SQLLoad failed," + this); } } catch (InterruptedException e) { logger.error("ORACLE SQLLoad interrupted.", e); } } catch (IOException e) { logger.error(e.getMessage(), e); } return result; } }
4、建立数据库连接java代码
package com.handaer.pro; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; public class OracleConnection { private static OracleConnection oracleConnection = null; private OracleConnection() { } public static final OracleConnection getOracleConnectionInstance() { if (oracleConnection == null) { oracleConnection = new OracleConnection(); } return oracleConnection; } private Statement st = null; private Connection connection = null; private ResultSet rs = null; static { try { Class.forName("oracle.jdbc.driver.OracleDriver"); System.out.println("加载驱动..."); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public Connection buildConnection(String url, String userName, String password) { try { connection = DriverManager.getConnection(url, userName, password); System.out.println("创建连接..."); } catch (SQLException e) { e.printStackTrace(); } return connection; } public Statement buildStatement(Connection connection) { try { st = connection.createStatement(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return st; } public void executeSql(String sql, int type) { try { st.executeUpdate(sql); } catch (SQLException e) { if (type == 1) { System.out.println("table之间有关联"); } else { e.printStackTrace(); } } } public List<String> executeQuery(String sql, String field) { List<String> tableList = new ArrayList<String>(); try { rs = st.executeQuery(sql); while (rs.next()) { tableList.add(rs.getString(field)); } } catch (SQLException e) { e.printStackTrace(); } return tableList; } public void close() { try { if (rs != null) { rs.close(); } if (st != null) { st.close(); } if (connection != null) { connection.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("关闭连接...."); } }
5、测试程序
package com.handaer.pro.server; import java.sql.Connection; import java.util.List; import com.handaer.pro.OracleConnection; import com.handaer.pro.OracleHelper; import com.handaer.pro.xml.PaserXml; public class StartServer { /** * ---------------------------原始库信息---------------------------------------- * ---- */ public static String expuserName = "pms"; public static String exppassword = "pmspwd"; public static String exportip = "192.168.0.122"; /** * ---------------------------目的库信息---------------------------------------- * ---- */ public static String impuserName = "pms"; public static String imppassword = "pmspwd"; public static String url = "jdbc:oracle:thin:@192.168.0.123:1521:orcl"; public static String impIp = "192.168.0.123"; public static String impSidNum = "orcl.localdomain"; /** * -----------------------------系统管理员-------------------------------------- * ----- */ public static String systemName = "system"; public static String systempassword = "handaer"; /** * ------------------------------SID号-------------------------------------- * --- */ public static String sidNum = "orcl"; public static String filePath = "D:\\exp\\pms.dmp"; /** * @param args */ public static void main(String[] args) { System.out.println("------------------------begin--------------------------------"); // 导入目的表之前先删除表 deleteTableSql(); System.out.println("---------------------delete all table------------------------"); // 删除目的表所有sequence deleteSequenceSql(); System.out.println("--------------------delete all sequence-----------------------"); expDbInfo(); System.out.println("---------------------------end exp----------------------------"); impDbInfo(); System.out.println("----------------------------end imp-----------------------------"); PaserXml paserXml = new PaserXml(); List<String> sqlList = paserXml.initXml(); System.out.println("-------------------------end init xml--------------------------"); changeDbData(sqlList); System.out.println("-------------------------end modify data------------------------"); System.out.println("-------------------------------end------------------------------"); } /** * 导出原始库 */ private static void expDbInfo() { OracleHelper oracleHelper = new OracleHelper(); oracleHelper.setOracleType("exp"); StringBuilder sb = new StringBuilder(expuserName).append("/").append(exppassword).append("@").append(exportip).append("/").append(sidNum); oracleHelper.setOracleInstance(sb.toString()); oracleHelper.setFilePath(filePath); oracleHelper.setOwner(expuserName); oracleHelper.preform(1); } /** * 导入目的库 */ private static void impDbInfo() { OracleHelper oracleHelper = new OracleHelper(); oracleHelper.setOracleType("imp"); StringBuilder sb = new StringBuilder(systemName).append("/").append(systempassword).append("@").append(impIp).append("/").append(impSidNum); oracleHelper.setOracleInstance(sb.toString()); oracleHelper.setFilePath(filePath); oracleHelper.setUser(expuserName, impuserName); oracleHelper.preform(2); } /** * 修改权限数据库中的数据 * * @param sqlList */ private static void changeDbData(List<String> sqlList) { Connection connection = OracleConnection.getOracleConnectionInstance().buildConnection(url, impuserName, imppassword); OracleConnection.getOracleConnectionInstance().buildStatement(connection); for (String sql : sqlList) { OracleConnection.getOracleConnectionInstance().executeSql(sql, 0); } OracleConnection.getOracleConnectionInstance().close(); } /** * 删除目的库中所有表 */ private static void deleteTableSql() { Connection connection = OracleConnection.getOracleConnectionInstance().buildConnection(url, impuserName, imppassword); OracleConnection.getOracleConnectionInstance().buildStatement(connection); String sql = "select 'drop table ' || table_name ||chr(13)||chr(10) tablesql from user_tables"; List<String> tableList = OracleConnection.getOracleConnectionInstance().executeQuery(sql, "tablesql"); while (tableList.size() != 0) { for (String tablesql : tableList) { OracleConnection.getOracleConnectionInstance().executeSql(tablesql, 1); } tableList = OracleConnection.getOracleConnectionInstance().executeQuery(sql, "tablesql"); } OracleConnection.getOracleConnectionInstance().close(); } /** * 删除目的库中所有sequence */ private static void deleteSequenceSql() { Connection connection = OracleConnection.getOracleConnectionInstance().buildConnection(url, impuserName, imppassword); OracleConnection.getOracleConnectionInstance().buildStatement(connection); String sql = "select 'drop sequence ' || sequence_name ||chr(13)||chr(10) se from user_sequences"; List<String> tableList = OracleConnection.getOracleConnectionInstance().executeQuery(sql, "se"); for (String tablesql : tableList) { OracleConnection.getOracleConnectionInstance().executeSql(tablesql, 0); } OracleConnection.getOracleConnectionInstance().close(); } }
6、测试结果
解析xml生成sql的结果如下:
UPDATE BUSINESS_SYSTEM SET IP='xxxx.xxxx.xxxx.xxxx' , PORT='40009' WHERE id=2 UPDATE BUSINESS_SYSTEM SET IP='xxxx.xxxx.xxxx.xxxx' , PORT='40001' WHERE id=3 UPDATE BUSINESS_SYSTEM SET IP='xxxx.xxxx.xxxx.xxxx' , PORT='40004' WHERE id=101 UPDATE BUSINESS_SYSTEM SET IP='xxxx.xxxx.xxxx.xxxx' , PORT='8080' WHERE id=121 UPDATE BUSINESS_SYSTEM SET IP='xxxx.xxxx.xxxx.xxxx' , PORT='40001' WHERE id=141 UPDATE BUSINESS_SYSTEM SET IP='xxxx.xxxx.xxxx.xxxx' , PORT='40006' WHERE id=161 UPDATE BUSINESS_SYSTEM SET IP='xxxx.xxxx.xxxx.xxxx' , PORT='40013' WHERE id=201 UPDATE BUSINESS_SYSTEM SET IP='xxxx.xxxx.xxxx.xxxx' , PORT='40014' WHERE id=202 UPDATE BUSINESS_SYSTEM SET IP='xxxx.xxxx.xxxx.xxxx' , PORT='40023' WHERE id=242 UPDATE BUSINESS_SYSTEM SET IP='xxxx.xxxx.xxxx.xxxx' , PORT='40010' WHERE id=241 UPDATE PROPERTY_VALUE SET VALUE='jdbc:oracle:thin:@xxxx.xxxx.xxxx.xxxx:1521:orcl' WHERE PROPERTY_VALUE_ID=12 UPDATE PROPERTY_VALUE SET VALUE='jdbc:oracle:thin:@xxxx.xxxx.xxxx.xxxx:1521:orcl' WHERE PROPERTY_VALUE_ID=38 UPDATE PROPERTY_VALUE SET VALUE='192.168.0.112' WHERE PROPERTY_VALUE_ID=13 UPDATE PROPERTY_VALUE SET VALUE='http://192.168.0.104/' WHERE PROPERTY_VALUE_ID=45 UPDATE PROPERTY_VALUE SET VALUE='http://xxxx.xxxx.xxxx.xxxx:40000' WHERE PROPERTY_VALUE_ID=74 UPDATE PROPERTY_VALUE SET VALUE='xxxx.xxxx.xxxx.xxxx' WHERE PROPERTY_VALUE_ID=5 UPDATE PROPERTY_VALUE SET VALUE='40000' WHERE PROPERTY_VALUE_ID=6 UPDATE BG_PROPERTY_VALUE SET VALUE='jdbc:oracle:thin:@xxxx.xxxx.xxxx.xxxx:1521:orcl' WHERE BG_PROPERTY_VALUE_ID=2 UPDATE BG_PROPERTY_VALUE SET VALUE='http://xxxx.xxxx.xxxx.xxxx:40018/' WHERE BG_PROPERTY_VALUE_ID=62 UPDATE BG_PROPERTY_VALUE SET VALUE='http://192.168.0.104:8081/dfs/ws/imgSys' WHERE BG_PROPERTY_VALUE_ID=64 UPDATE BG_PROPERTY_VALUE SET VALUE='http://xxxx.xxxx.xxxx.xxxx:40018/' WHERE BG_PROPERTY_VALUE_ID=65 UPDATE BG_PROPERTY_VALUE SET VALUE='jdbc:oracle:thin:@xxxx.xxxx.xxxx.xxxx:1521:orcl' WHERE BG_PROPERTY_VALUE_ID=69 UPDATE BG_PROPERTY_VALUE SET VALUE='jdbc:oracle:thin:@xxxx.xxxx.xxxx.xxxx:1521:orcl' WHERE BG_PROPERTY_VALUE_ID=32 -------------------------end init xml--------------------------