Last active
April 8, 2018 13:52
-
-
Save nwillc/e7bc53e5c3c218e6da0208b885fdd089 to your computer and use it in GitHub Desktop.
JDBC generated keys: Attempt 1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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