2016-09-24 31 views
0

我想選擇紅移表約100萬條記錄,然後需要插入回那些紅移表(做一些操作後)如何做選擇並插入萬條記錄,通過java程序更快

但是,這需要很長時間。我等了大約1小時,程序終止了,但沒有運氣。控制檯也似乎不打印print statements,但打印幾條語句後似乎卡住了。

試了100條記錄,它工作正常,大約需要2分鐘。

這是我的代碼部分:

 conn.setAutoCommit(false); 
     stmt = conn.createStatement(); 
     stmt.setFetchSize(100); 
     ResultSet rsSelect = stmt.executeQuery("select * from table"); 
     System.out.println("select done !"); 

     String queryInsert = "insert into table" 
       +"(event_id,domain_userid,collector_tstamp,se_category,se_action,se_label,se_property)" 
       +"values(?,?,?,?,?,?,?)"; 

     PreparedStatement preparedStatement = conn.prepareStatement(queryInsert); 
     final int batchSize = 10000; 
     int count = 0; 
     System.out.println("about to go into loop !"); 


     while(rsSelect.next()){ 

      String event_id = rsSelect.getString("event_id"); 
      String domain_userid = rsSelect.getString("domain_userid"); 
      Timestamp collector_tstamp = rsSelect.getTimestamp("collector_tstamp"); 
      String se_category = rsSelect.getString("se_category"); 
      String se_action = rsSelect.getString("se_action"); 
      String se_label = rsSelect.getString("se_label"); 
      String se_property = rsSelect.getString("se_property"); 

      //some manipulations 

      preparedStatement.setString(1, event_id); 
      preparedStatement.setString(2, domain_userid); 
      preparedStatement.setTimestamp(3, collector_tstamp); 
      preparedStatement.setString(4, se_category); 
      preparedStatement.setString(5, se_action); 
      preparedStatement.setString(6, se_label);       
      preparedStatement.setString(7, se_property); 
      preparedStatement.addBatch(); 

      if(++count % batchSize == 0){ 
       preparedStatement.executeBatch(); 
       System.out.println("batch execution!"); 

      }    
     } 
     System.out.println("out of loop"); 
     preparedStatement.executeBatch(); 
     preparedStatement.close(); 
     conn.commit(); 
     conn.close(); 
+0

http://stackoverflow.com/questions/6892105/bulk-insert-in-java-using-prepared-statements-batch-update – Pradeep

+0

我用巴赫插入@Pradeep –

+0

使用BULK INSERT - 它是專爲準確你在問什麼,並顯着提高插入速度。 此外,(如果你確實沒有索引),你可能還想考慮添加一個索引 - 一些索引(大多數索引在主鍵上)可以提高插入的性能。 你應該能夠插入記錄的實際速率取決於確切的數據,表結構以及SQL服務器本身的硬件/配置,所以我不能給你任何數字。 – Pradeep

回答

0

我有同樣的問題,時間太長,從一個紅移表中插入數據到另一個紅移表(我用的node.js)。最初,我花了大約18分鐘來插入100萬條記錄。

我想我的表中的數據沒有按排序鍵(時間戳)排序。必須按照排序鍵對數據進行排序,並在where謂詞中使用該排序鍵(如果有where謂詞)。
Run vacuum table to 100 percent
對數據進行排序。在你的操作之後,確保你按照你的排序鍵排序。

這樣做後,我能夠實現意想不到的結果。在3秒內插入100萬條記錄。

+0

謝謝@Redshift Guy。我一定會試一試並分享一下結果。 –

相關問題