Advertisement
Guest User

Untitled

a guest
Mar 20th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.81 KB | None | 0 0
  1. package sk.tuke.gamestudio.service;
  2.  
  3. import sk.tuke.gamestudio.entity.Rating;
  4.  
  5. import java.sql.*;
  6.  
  7. public class RatingServiceJDBC implements RatingService {
  8.  
  9. public static final String URL = "jdbc:postgresql://localhost/gamestudio";
  10. public static final String USER = "postgres";
  11. public static final String PASSWORD = "postgres";
  12.  
  13. public static final String INSERT_RATING =
  14. "INSERT INTO rating (game, player, rating, ratedon) VALUES (?, ?, ?, ?)";
  15.  
  16. public static final String SELECT_RATING =
  17. "SELECT game, player, rating, ratedon FROM rating;";
  18.  
  19.  
  20. @Override
  21. public void setRating(Rating rating) throws RatingException {
  22. try(Connection connection = DriverManager.getConnection(URL, USER, PASSWORD)) {
  23. try(PreparedStatement ps = connection.prepareStatement(INSERT_RATING)) {
  24. ps.setString(1, rating.getGame());
  25. ps.setString(2, rating.getPlayer());
  26. ps.setInt(3, rating.getRating());
  27. ps.setDate(4, new Date(rating.getRatedon().getTime()));
  28.  
  29. ps.execute();
  30. }
  31. } catch (SQLException e) {
  32. throw new RatingException("Error saving rating", e);
  33. }
  34. }
  35.  
  36.  
  37. @Override
  38. public int getAverageRating(String game) throws RatingException {
  39. int sumRating = 0;
  40. int size = 0;
  41. try(Connection connection = DriverManager.getConnection(URL, USER, PASSWORD)) {
  42. try(PreparedStatement ps = connection.prepareStatement(SELECT_RATING)) {
  43. try(ResultSet rs = ps.executeQuery()) {
  44. while(rs.next()) {
  45. if(rs.getString(1).equals(game)) {
  46. size++;
  47. sumRating += rs.getInt(3);
  48. }
  49. }
  50. }
  51.  
  52. }
  53. } catch (SQLException e) {
  54. throw new RatingException("Cant get avarage rating", e);
  55. }
  56. return sumRating/size;
  57. }
  58.  
  59. @Override
  60. public int getRating(String game, String player) throws RatingException {
  61. int rating = -1;
  62. try(Connection connection = DriverManager.getConnection(URL, USER, PASSWORD)) {
  63. try(PreparedStatement ps = connection.prepareStatement( SELECT_RATING)) {
  64. try(ResultSet rs = ps.executeQuery()) {
  65. while (rs.next()) {
  66. if(rs.getString(1).equals(game) && rs.getString(2).equals(player)) {
  67. rating = rs.getInt(3);
  68. break;
  69. }
  70. }
  71. }
  72. }
  73. } catch (SQLException e) {
  74. throw new RatingException("Cant get rating", e);
  75. }
  76. return rating;
  77. }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement