Skip to content

Instantly share code, notes, and snippets.

@nwillc
Created April 9, 2018 03:02
Show Gist options
  • Save nwillc/895671bc7ca25da5f910caf6c95770a3 to your computer and use it in GitHub Desktop.
Save nwillc/895671bc7ca25da5f910caf6c95770a3 to your computer and use it in GitHub Desktop.
Attempt 2 at more portable key retrieval
public long create(String sql, String[] keyColumns) throws SQLException {
try (
Connection connection = dataSource.getConnection();
PreparedStatement statement = connection.prepareStatement(sql, keyColumns)) {
if (statement.execute() == 0) {
throw new SQLException("Insert failed, no rows affected.");
}
try (ResultSet generatedKeys = statement.getGeneratedKeys()) {
if (generatedKeys.next()) {
return generatedKeys.getLong(1);
} else {
throw new SQLException("Creating user failed, no ID obtained.");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment