2013-08-21 71 views
0

我正在通过SQL查询('SELECT_PROCESS_INITIAL_REQUEST')创建结果集,它基本上只是抓取了SQL数据库表中的所有内容。如何将结果集数据转储到数据库表

Statement stmt = conn.createStatement(); 
String sql = SQLDataAdaptor.SELECT_PROCESS_INITIAL_REQUEST; 
ResultSet rsRequest = stmt.executeQuery(sql); 

然后我想将该数据转储到与原始数据库相同的表中,但在不同的数据库中。我会怎么做?

+0

使用2种不同'Connections',一个指向源数据库和其他定位到目标数据库,并使用批量插入来处理工作。无论如何,如果可以的话,最好使用像Pentaho这样的ETL工具 –

+0

您应该执行类似于[this(using MySQL)]中给出的语句(http://www.tech-recipes.com/rx/) 1487 /复制一个存在的MySQL的表到一个新表/)。因为你没有修改任何数据。 –

回答

0

将它转储到另一个数据库中意味着Java将不得不处理您的结果集。所以我很害怕你必须以编程的方式做到这一点。

想想“准备好的语句”,“添加批处理方法”,并且不要忘记每n条记录执行插入操作。

0

使用的Java教程网站 - 的例子

public static void viewTable(Connection con, String dbName) 
throws SQLException { 

    //Modify this code according to 2nd database vendor and credentials- 
      String url = "jdbc:sqlserver://MYPC\\SQLEXPRESS;databaseName=MYDB;integratedSecurity=true"; 
      Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); 
      Connection conn2 = DriverManager.getConnection(url); 

    Statement stmt = null; 
    Statement insertStmt = null; 
    String query = "select COF_NAME, SUP_ID, PRICE, " + 
       "SALES, TOTAL " + 
       "from " + dbName + ".COFFEES"; 
    try { 
     stmt = con.createStatement(); 
     insertStmt = conn2.createStatement(); 
     ResultSet rs = stmt.executeQuery(query); 
     while (rs.next()) { 
      String coffeeName = rs.getString("COF_NAME"); 
      int supplierID = rs.getInt("SUP_ID"); 
      float price = rs.getFloat("PRICE"); 
      int sales = rs.getInt("SALES"); 
      int total = rs.getInt("TOTAL"); 

      String insertQuery = "INSERT INTO COFFEES (COF_NAME, SUP_ID, PRICE, sales, total) VALUES (coffeeName,supplierID, proce, sales, total); 

      try{ 
       insertStmt.execute(insertQuery); 

      }catch(SQLExeption e){ 
       e.printStackTrace(); 
      } 
     } 
    } catch (SQLException e) { 
     e.printStackTrace(); 
    } finally { 
     if (stmt != null) { stmt.close();} 
     if(insertStmt != null) {insertStmt.close();} 
    } 
} 
+0

你应该把负责连接的代码放在循环之外,因为在你的情况下,每一行都会建立一个新的连接到数据库,这是巨大的! –

+0

@ alaeddine.nasri - 绝对!....感谢您指出! – Aniket

相关问题