Skip to content

Instantly share code, notes, and snippets.

@dusanstanojeviccs
Created November 5, 2017 22:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dusanstanojeviccs/40a1cacf7fb1adf39b6fe1ec60880694 to your computer and use it in GitHub Desktop.
Save dusanstanojeviccs/40a1cacf7fb1adf39b6fe1ec60880694 to your computer and use it in GitHub Desktop.
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