Advertisement
tomschuyten

BeerDAO

Mar 22nd, 2016
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.93 KB | None | 0 0
  1. private String url;
  2. private String user;
  3. private String password;
  4. public BeerDao () {
  5. }
  6. public BeerDao(String url, String user, String password) {
  7.    this.url = url;
  8.    this.user = user;
  9.    this.password = password;
  10. }
  11. public String getUrl() {
  12. return url; }
  13. public void setUrl(String url) {
  14.    this.url = url;
  15. }
  16. public String getUser() {
  17.    return user;
  18. }
  19. public void setUser(String user) {
  20.    this.user = user;
  21. }
  22. public String getPassword() {
  23.    return password;
  24. }
  25. public void setPassword(String password) {
  26.    this.password = password;
  27. }
  28. public Beer getBeerById(int id) throws BeerException { try (Connection con = getConnection();
  29.          PreparedStatement stmt = con
  30.           .prepareStatement("SELECT * FROM Beers WHERE Id=?")) {
  31.       stmt.setInt(1, id);
  32.       try (ResultSet rs = stmt.executeQuery()) {
  33.          if (rs.next()) {
  34.             Beer beer = new Beer();
  35.             beer.setId(id);
  36.             beer.setName(rs.getString("Name"));
  37.             beer.setPrice(rs.getFloat("Price"));
  38.             beer.setAlcohol(rs.getFloat("Alcohol"));
  39.             beer.setStock(rs.getInt("Stock"));
  40.             return beer;
  41. } else {
  42.             return null;
  43.          }
  44.       }
  45.    } catch (SQLException e) {
  46.       throw new BeerException(e);
  47.    }
  48. }
  49.  
  50. public void updateBeer(Beer beer) throws BeerException { try (Connection con = getConnection();
  51.             PreparedStatement stmt = con
  52.               .prepareStatement("UPDATE Beers SET Name=?, Price=?,
  53. Alcohol=?, Stock=?  WHERE Id=?")) {
  54. stmt.setString(1, beer.getName()); stmt.setFloat(2, beer.getPrice()); stmt.setFloat(3, beer.getAlcohol()); stmt.setInt(4, beer.getStock()); stmt.setInt(5, beer.getId()); stmt.executeUpdate();
  55.       } catch (SQLException e) {
  56.          throw new BeerException(e);
  57.       }
  58. }
  59.    // Private helper methods
  60.    private Connection getConnection() throws SQLException {
  61.       return DriverManager.getConnection(url,user,password);
  62.    }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement