Created
November 5, 2017 22:06
-
-
Save dusanstanojeviccs/40a1cacf7fb1adf39b6fe1ec60880694 to your computer and use it in GitHub Desktop.
This file contains 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 void add(Book book) throws SQLException { | |
// Book has no id because we are adding a new one to the database | |
PreparedStatement preparedStatement = database.getConnection().prepareStatement("insert into books (id, title, description) values (null, ?, ?)", Statement.RETURN_GENERATED_KEYS); | |
preparedStatement.setString(1, book.getTitle()); | |
preparedStatement.setString(2, book.getDescription()); | |
preparedStatement.execute(); | |
// after inserting we want to get the generated id | |
ResultSet rs = preparedStatement.getGeneratedKeys(); | |
if (rs.next()) { | |
book.setId(rs.getInt(1)); | |
} | |
preparedStatement.executeUpdate(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment