jdbc有效地生成了Keys以及其他数据

时间:2011-10-27 18:21:00

标签: jdbc batch-file

批量插入多行后,我希望检索生成的键及其对应的插入行。我该如何有效地做到这一点?由于我可以使用statement.getGeneratedKeys()根据每个生成的id查询每行的数据库,但这似乎很慢。
下面的代码执行批量插入,然后遍历表中的所有结果,但是我不希望在插入之前包含表中已存在的数据。
还有其他选择吗?


      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 个答案:

答案 0 :(得分:0)

您有一个感兴趣的ID列表。您可以使用“ ID in(...,...,)”约束:

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