0
votes

After batch insert a number of rows, I wish to retrieve the generated keys along with their corresponding inserted rows. how do I do this efficiently?
Naively I can use statement.getGeneratedKeys() to query the database for each row based on each generated id, but that seems slow.
the code below does a batch insert and then go through all the results in the table, however I don't want to include data that already exists in the table prior to insertion.
is there an alternative?


      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();
        }
      }

1

1 Answers

0
votes

You have a list of IDs you are interested in. You can use the 'id in (...,...,)' constraint:

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+")");
  ...
}