Created
April 9, 2018 03:02
-
-
Save nwillc/895671bc7ca25da5f910caf6c95770a3 to your computer and use it in GitHub Desktop.
Attempt 2 at more portable key retrieval
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, 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