Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package sk.tuke.gamestudio.service;
- import sk.tuke.gamestudio.entity.Rating;
- import java.sql.*;
- public class RatingServiceJDBC implements RatingService {
- public static final String URL = "jdbc:postgresql://localhost/gamestudio";
- public static final String USER = "postgres";
- public static final String PASSWORD = "postgres";
- public static final String INSERT_RATING =
- "INSERT INTO rating (game, player, rating, ratedon) VALUES (?, ?, ?, ?)";
- public static final String SELECT_RATING =
- "SELECT game, player, rating, ratedon FROM rating;";
- @Override
- public void setRating(Rating rating) throws RatingException {
- try(Connection connection = DriverManager.getConnection(URL, USER, PASSWORD)) {
- try(PreparedStatement ps = connection.prepareStatement(INSERT_RATING)) {
- ps.setString(1, rating.getGame());
- ps.setString(2, rating.getPlayer());
- ps.setInt(3, rating.getRating());
- ps.setDate(4, new Date(rating.getRatedon().getTime()));
- ps.execute();
- }
- } catch (SQLException e) {
- throw new RatingException("Error saving rating", e);
- }
- }
- @Override
- public int getAverageRating(String game) throws RatingException {
- int sumRating = 0;
- int size = 0;
- try(Connection connection = DriverManager.getConnection(URL, USER, PASSWORD)) {
- try(PreparedStatement ps = connection.prepareStatement(SELECT_RATING)) {
- try(ResultSet rs = ps.executeQuery()) {
- while(rs.next()) {
- if(rs.getString(1).equals(game)) {
- size++;
- sumRating += rs.getInt(3);
- }
- }
- }
- }
- } catch (SQLException e) {
- throw new RatingException("Cant get avarage rating", e);
- }
- return sumRating/size;
- }
- @Override
- public int getRating(String game, String player) throws RatingException {
- int rating = -1;
- try(Connection connection = DriverManager.getConnection(URL, USER, PASSWORD)) {
- try(PreparedStatement ps = connection.prepareStatement( SELECT_RATING)) {
- try(ResultSet rs = ps.executeQuery()) {
- while (rs.next()) {
- if(rs.getString(1).equals(game) && rs.getString(2).equals(player)) {
- rating = rs.getInt(3);
- break;
- }
- }
- }
- }
- } catch (SQLException e) {
- throw new RatingException("Cant get rating", e);
- }
- return rating;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement