Skip to content

Instantly share code, notes, and snippets.

@nwillc
Last active April 8, 2018 13:52
Show Gist options
  • Save nwillc/e7bc53e5c3c218e6da0208b885fdd089 to your computer and use it in GitHub Desktop.
Save nwillc/e7bc53e5c3c218e6da0208b885fdd089 to your computer and use it in GitHub Desktop.
JDBC generated keys: Attempt 1
public long create(String sql) throws SQLException {
try (
Connection connection = dataSource.getConnection();
Statement statement = connection.prepareStatement(sql,
Statement.RETURN_GENERATED_KEYS)) {
if (statement.executeUpdate() == 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