Advertisement
Guest User

Untitled

a guest
Mar 16th, 2016
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.55 KB | None | 0 0
  1. package sk.tuke.kp.bricksbreaker.Service;
  2.  
  3. import sk.tuke.kp.bricksbreaker.Entity.FavouriteGame;
  4.  
  5. import java.sql.*;
  6. import java.sql.Date;
  7. import java.util.*;
  8.  
  9. /**
  10. * Created by jakubcervenak on 16/03/16.
  11. */
  12. public class FavouriteServiceImpl implements FavouriteService {
  13. private static final String URL = "jdbc:postgresql://localhost/codermakac";
  14. private static final String LOGIN = "postgres";
  15. private static final String PASSWORD = "pomaranc";
  16.  
  17. private static final String INSERT_STMT =
  18. "INSERT INTO favourites (player, game, date) VALUES (?, ?, ? )";
  19.  
  20. private static final String SELECT_STMT =
  21. "SELECT player, game, date FROM favourites WHERE player = ? ORDER BY player ASC";
  22. @Override
  23. public void addFavourite(FavouriteGame favouriteGame) throws FavouriteException {
  24. try(Connection connection = DriverManager.getConnection(URL, LOGIN, PASSWORD);
  25. PreparedStatement ps = connection.prepareStatement(INSERT_STMT)) {
  26. ps.setString(1, favouriteGame.getPlayer());
  27. ps.setString(2, favouriteGame.getGame());
  28.  
  29. ps.setDate(3, new java.sql.Date(favouriteGame.getDate().getTime()));
  30. ps.executeUpdate();
  31. } catch (SQLException e) {
  32. throw new FavouriteException("Error saving favourites", e);
  33. }
  34.  
  35. }
  36.  
  37. @Override
  38. public List<FavouriteGame> getFavouriteGame(String player) throws FavouriteException {
  39. List<FavouriteGame> favourites = new ArrayList<>();
  40.  
  41. try(Connection connection = DriverManager.getConnection(URL, LOGIN, PASSWORD);
  42. PreparedStatement ps = connection.prepareStatement(SELECT_STMT)) {
  43. ps.setString(1, player);
  44. try(ResultSet rs = ps.executeQuery()) {
  45. while(rs.next()) {
  46. FavouriteGame favouriteGame = new FavouriteGame(rs.getString(1), rs.getString(2),
  47. rs.getDate(3));
  48. favourites.add(favouriteGame);
  49. }
  50. }
  51. } catch (SQLException e) {
  52. throw new FavouriteException("Error loading favourites", e);
  53. }
  54.  
  55. return favourites;
  56. }
  57.  
  58. public static void main(String[] args) throws FavouriteException {
  59. FavouriteGame favourite = new FavouriteGame("jacky", "bricks",new java.util.Date());
  60. FavouriteService favouriteService = new FavouriteServiceImpl();
  61. favouriteService.addFavourite(favourite);
  62. System.out.println(favouriteService.getFavouriteGame("jacky"));
  63. }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement