標籤:style io os ar java for 檔案 資料 sp
在oarcle的sql指令碼中欄位長度超過4000執行會有異常,而在postgresql中超過4000仍可以正常執行,產品同時支援多個資料庫,如oracle和postgresql,在基礎資料較多時,只能通過匯出基礎資料相關表的dmp或backup檔案進行升級部署。開發的時候以oracle作為開發庫,需要將基礎資料弄到postgresql製作backup檔案,通過程式直接讀oracle表寫到postgresql。
步驟:
1、修改oracle和postgresql庫的ip、使用者名稱和密碼;
2、修改庫表列表;
3、運行;
public static void main(String[] args) throws Exception{ long t0 = System.currentTimeMillis(); Class.forName("oracle.jdbc.driver.OracleDriver"); Class.forName("org.postgresql.Driver"); Connection srcCon = null, dstCon = null; Statement srcStmt = null, dstStmt= null; PreparedStatement ps = null; try{ /*建立串連*/ srcCon = DriverManager.getConnection("jdbc:oracle:thin:@192.168.1.12:1521:orcl", "h2do", "h2do"); dstCon = DriverManager.getConnection("jdbc:postgresql://192.168.1.23:5432/h2do", "postgres", "postgres"); srcStmt = srcCon.createStatement(); dstStmt = dstCon.createStatement(); /*庫表列表*/ String[] tables = new String[]{ "h2do", "e2say" }; /*逐表處理*/ for(String table : tables) { /*1、清理目標表*/ dstStmt.execute("truncate table " + table); /*2、查詢源表欄位拼接預先處理SQL語句*/ ResultSet rs = srcStmt.executeQuery("select * from " + table); StringBuilder sql1 = new StringBuilder("insert into " + table + "("); StringBuilder sql2 = new StringBuilder(") values ("); ResultSetMetaData rsmd = rs.getMetaData(); for(int col = 1; col <= rsmd.getColumnCount(); col++) { if(col > 1){ sql1.append(","); sql2.append(","); } sql1.append(rsmd.getColumnName(col).toLowerCase()); sql2.append("?"); } String sql = sql1.toString() + sql2.toString() + ")"; System.out.println(sql); /*3、讀取源表資料插入目標表,每千條提交一次*/ int rows = 0; ps = dstCon.prepareStatement(sql); while(rs.next()) { for(int col = 1; col <= rsmd.getColumnCount(); col++) { if(rsmd.getColumnType(col) == Types.CLOB){ ps.setString(col, rs.getString(col)); }else{ ps.setObject(col, rs.getObject(col)); } } ps.addBatch(); rows++; if(rows%1000 == 0) { ps.executeBatch(); dstCon.commit(); ps.clearBatch(); rows = 0; } } if(rows > 0){ ps.executeBatch(); dstCon.commit(); } ps.close(); System.out.println("耗時:" + (System.currentTimeMillis() - t0) + "毫秒(" + table + ")。"); } }finally{ try{if(null != srcStmt)srcStmt.close();}catch(Exception e){} try{if(null != srcCon )srcCon.close(); }catch(Exception e){} try{if(null != dstStmt)dstStmt.close();}catch(Exception e){} try{if(null != dstCon )dstCon.close(); }catch(Exception e){} } System.out.println("總耗時:" + (System.currentTimeMillis() - t0) + "毫秒。");}
從oracle遷移帶clob欄位的表資料至postgresql