Advertisement
Guest User

Untitled

a guest
Nov 28th, 2018
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 6.55 KB | None | 0 0
  1. package importadorbases;
  2.  
  3. import java.sql.*;
  4. import java.util.ArrayList;
  5. import java.util.List;
  6. import java.util.stream.Collectors;
  7.  
  8. /**
  9.  *
  10.  * @author emerson.engroff
  11.  */
  12. public class ImportadorBases {
  13.  
  14.     public static void main(String[] args) throws SQLException {
  15.  
  16.         String conexaoOrigem = "";
  17.         String conexaoDestino = "";
  18.         String tabelasExcluir = "";
  19.         String tabelasIncluir = "";
  20.  
  21.         for (int i = 0; i < args.length; i++) {
  22.             if (args[i].equals("-o")) {
  23.                 conexaoOrigem = args[i + 1];
  24.             } else if (args[i].equals("-d")) {
  25.                 conexaoDestino = args[i + 1];
  26.             } else if (args[i].equals("-T")) {
  27.                 tabelasExcluir = args[i + 1];
  28.             } else if (args[i].equals("-t")) {
  29.                 tabelasIncluir = args[i + 1];
  30.             }
  31.         }
  32.  
  33.         if (conexaoOrigem.equals("") || conexaoDestino.equals("")) {
  34.             System.out.println("paramentros: -o conexao de origem -d conexao de destino -t(opcional) regex tabelas a incluir -T(opcional) regex tabelas a excluir");
  35.             System.out.println("formanto conexao: jdbc:DRIVER:HOST:PORTA|USUARIO|SENHA|ESQUEMA(opcional)");
  36.             System.out.println(
  37.                     "Ex: java -jar importadorBases.jar"
  38.                     + " -o \"jdbc:sybase:Tds:10.1.1.133:50768|externo|123456|\""
  39.                     + " -d \"jdbc:postgresql://marte.solucoesglobais.com.br:5432/conversao_betha|postgres|postgres|conversao\""
  40.                     + " -t \"^tomasi.*\" -T \"^tomasi\\.pb.*\"; "
  41.             );
  42.         }
  43.  
  44.         Connection conn1 = openDatabase(conexaoOrigem);
  45.         Connection conn2 = openDatabase(conexaoDestino);
  46.  
  47.         ResultSet resultSet = conn1.getMetaData().getCatalogs();
  48.         String[] types = {"TABLE"};
  49.         resultSet = conn1.getMetaData().getTables(conn1.getCatalog(), null, "%", types);
  50.  
  51.         String table;
  52.  
  53.         while (resultSet.next()) {
  54.             table = "" + resultSet.getString(2) + "." + resultSet.getString(3) + "";
  55.             if (!tabelasIncluir.equals("") && !table.toLowerCase().matches(tabelasIncluir)) {
  56.                 continue;
  57.             }
  58.             if (!tabelasExcluir.equals("") && table.toLowerCase().matches(tabelasExcluir)) {
  59.                 continue;
  60.             }
  61.             copyTable(table, conn1, conn2);
  62.         }
  63.  
  64.         resultSet.close();
  65.  
  66.         closeDatabase(conn1);
  67.         closeDatabase(conn2);
  68.     }
  69.  
  70.     public static void copyTable(String table, Connection conn1, Connection conn2) throws SQLException {
  71.         System.out.print("Copiando '" + table + "' ");
  72.         try {
  73.             PreparedStatement s1 = conn1.prepareStatement("SELECT * FROM " + table + ";");
  74.             ResultSet rs = s1.executeQuery();
  75.  
  76.             ResultSetMetaData meta = rs.getMetaData();
  77.             Integer columnCount = meta.getColumnCount();
  78.             Integer k = 0;
  79.             Integer j = 0;
  80.             String table2 = table.replace(".", "_");
  81.  
  82.             List<String> columns = new ArrayList<>();
  83.             for (int i = 1; i <= columnCount; i++) {
  84.                 columns.add(meta.getColumnName(i));
  85.             }
  86.  
  87.             conn2.createStatement().execute("CREATE TABLE \"" + table2 + "\" (\"" + columns.stream().collect(Collectors.joining("\" TEXT, \"")) + "\" TEXT);");
  88.  
  89.             try (PreparedStatement s2 = conn2.prepareStatement(
  90.                     "INSERT INTO " + table2 + " (\""
  91.                     + columns.stream().collect(Collectors.joining("\", \""))
  92.                     + "\") VALUES ("
  93.                     + columns.stream().map(c -> "?").collect(Collectors.joining(", "))
  94.                     + ");"
  95.             )) {
  96.  
  97.                 while (rs.next()) {
  98.                     k++;
  99.                     j++;
  100.                     for (int i = 1; i <= columnCount; i++) {
  101.                         s2.setObject(i, rs.getObject(i));
  102.                     }
  103.                     s2.addBatch();
  104.                     if (k == 1000) {
  105.                         s2.executeBatch();
  106.                         System.gc();
  107.                         k = 0;
  108.                     }
  109.                 }
  110.                 s2.executeBatch();
  111.                 rs.close();
  112.                 System.gc();
  113.             }
  114.             System.out.println("OK "+j+" registros");
  115.         } catch (SQLException e) {
  116.             System.out.println("Erro: nao foi possivel copiar '" + table + "' - [" + e.getSQLState() + "] " + e.toString());
  117.         }
  118.  
  119.     }
  120.  
  121.     public static Connection openDatabase(String connString) {
  122.         connString += "|-";
  123.         String[] connDataArr = connString.split("\\|");
  124.         String strDriver = "";
  125.         String strURL = connDataArr[0];
  126.         String strUserId = connDataArr[1];
  127.         String strUserPswd = connDataArr[2];
  128.         String strSchema = connDataArr[3];
  129.  
  130.         Connection conn;
  131.  
  132.         if (strURL.matches(".*postgresql.*")) {
  133.             strDriver = "org.postgresql.Driver";
  134.         } else if (strURL.matches(".*sybase.*")) {
  135.             strDriver = "com.sybase.jdbc3.jdbc.SybDriver";
  136.         }
  137.  
  138.         try {
  139.             Class drvClass = Class.forName(strDriver);
  140.             DriverManager.registerDriver((Driver) drvClass.newInstance());
  141.             DriverManager.setLoginTimeout(900);//15 minutos de timeout
  142.             conn = DriverManager.getConnection(strURL, strUserId, strUserPswd);
  143.             if (!strSchema.equals("")) {
  144.                 conn.createStatement().execute(
  145.                         "CREATE SCHEMA \"" + strSchema + "\";"
  146.                         + "SET search_path TO \"" + strSchema + "\";"
  147.                 );
  148.             }
  149.         } catch (SQLException e) {
  150.             printSQLException(e);
  151.             return null;
  152.         } catch (ClassNotFoundException e) {
  153.             e.printStackTrace();
  154.             return null;
  155.         } catch (InstantiationException e) {
  156.             e.printStackTrace();
  157.             return null;
  158.         } catch (IllegalAccessException e) {
  159.             e.printStackTrace();
  160.             return null;
  161.         }
  162.  
  163.         return conn;
  164.     }
  165.  
  166.     public static boolean closeDatabase(Connection conn) {
  167.         if (conn == null) {
  168.             return true;
  169.         }
  170.         try {
  171.             conn.close();
  172.         } catch (SQLException e) {
  173.             return false;
  174.         }
  175.         return true;
  176.     }
  177.  
  178.     public static void printSQLException(SQLException e) {
  179.         e.printStackTrace();
  180.         while (e != null) {
  181.             System.out.println(e);
  182.             e = e.getNextException();
  183.         }
  184.     }
  185. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement