2011-10-27 14 views
0

バッチの後にいくつかの行を挿入した後、生成されたキーと対応する挿入行を取得します。どのようにこれを効率的に行うのですか?
Naive私は、各生成されたIDに基づいて各行のデータベースを照会するのにstatement.getGeneratedKeys()を使用することができますが、それは遅いようです。
以下のコードはバッチ挿入を実行してから、テーブル内のすべての結果を調べますが、挿入前に既にテーブルに存在するデータは含めたくありません。
代替手段がありますか?jdbcは効率的に他のデータと一緒に生成されます

 

     public static void main(String[] args) throws Exception { 
     Connection conn = getMySqlConnection(); 
     ResultSet rs = null; 
     Statement stmt = null; 
     try { 
      conn = getMySqlConnection(); 
      stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, 
             ResultSet.CONCUR_UPDATABLE); 
      conn.setAutoCommit(false); 
      stmt.addBatch("INSERT INTO survey(id, name) VALUES('11', 'Alex')"); 
      stmt.addBatch("INSERT INTO survey(id, name) VALUES('22', 'Mary')"); 
      stmt.addBatch("INSERT INTO survey(id, name) VALUES('33', 'Bob')"); 
      int[] updateCounts = stmt.executeBatch(); 
      System.out.println(updateCounts); 
      conn.commit(); 
      rs = stmt.executeQuery("SELECT * FROM survey"); 
      while (rs.next()) { 
       String id = rs.getString("id"); 
       String name = rs.getString("name"); 
       System.out.println("id="+id +" name="+name); 
      } 
     } 
     catch(BatchUpdateException b) { 
      System.err.println("SQLException: " + b.getMessage()); 
      System.err.println("SQLState: " + b.getSQLState()); 
      System.err.println("Message: " + b.getMessage()); 
      System.err.println("Vendor error code: " + b.getErrorCode()); 
      System.err.print("Update counts: "); 
      int [] updateCounts = b.getUpdateCounts(); 
      for (int i = 0; i < updateCounts.length; i++) { 
       System.err.print(updateCounts[i] + " "); 
      } 
     } 
     catch(SQLException ex) { 
      System.err.println("SQLException: " + ex.getMessage()); 
      System.err.println("SQLState: " + ex.getSQLState()); 
      System.err.println("Message: " + ex.getMessage()); 
      System.err.println("Vendor error code: " + ex.getErrorCode()); 
     } 
     catch(Exception e) { 
      e.printStackTrace(); 
      System.err.println("Exception: " + e.getMessage()); 
     } 
     finally { 
      rs.close(); 
      stmt.close(); 
      conn.close(); 
     } 
     } 

答えて

0

あなたは、あなたが興味を持っているIDのリストを持っているあなたは制約 '(...、...、)にID' を使用することができます。

StringBuilder newIds = new StringBuilder(); 
ResultSet rs = stmt.getGeneratedKeys(); 
while (rs.next()) { 
    if (newIds.length() > 0) newIds.append(','); 
    newIds.append(rs.getInt(1)); 
} 

if (newIds.length() >) { 
    rs = stmt.executeQuery("SELECT * FROM survey where id in ("+newIds+")"); 
    ... 
} 
関連する問題