简体   繁体   中英

How to retrieve all generated keys from multiple row PreparedStatement in Java?

Assuming the following SQL Statement:

INSERT INTO MATERIAL (ID, CODE, NAME) VALUES
(NULL, 'firstCode', 'firstName'),
(NULL, 'secondCode', 'secondName');

Using the follwing code where the PreparedStatement instance ps represents the SQL statement from above. And the PreparedStatement has been obtained with the option new String[]{"ID"} in order to specify the column name of the generated keys:

try {
    final int affectedRows = ps.executeUpdate();
    assertEquals("failed to insert all entries", "2", String.valueOf(affectedRows));
    final ResultSet generatedKeys = ps.getGeneratedKeys();
    while (generatedKeys.next()) {
      System.out.println(generatedKeys.getInt(1));
    }
} catch (SQLException e) {
    // some catch block
}

The problem is that only the ID of the second row will be retrieved. Do you have a suggestion how to retrieve all of the generated keys?

EDIT:

This is the table's definition.

CREATE TABLE IF NOT EXISTS "MATERIAL" (
  "ID" INT NOT NULL AUTO_INCREMENT,
  "IDMATERIAL" VARCHAR(5) NOT NULL,
  "NAME"       VARCHAR(100) NOT NULL
);

try this,

PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)
ResultSet rs = preparedStatement.getGeneratedKeys();

while(rs.next())
{
    System.out.println(rs.getLong(1));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM