Advertisement
Guest User

Untitled

a guest
Dec 9th, 2017
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.65 KB | None | 0 0
  1. package sk.tuke.gamestudio.service;
  2.  
  3. import sk.tuke.gamestudio.entity.Score;
  4.  
  5. import java.sql.*;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8.  
  9. /*
  10. CREATE TABLE score (
  11.     player VARCHAR(32) NOT NULL,
  12.     game VARCHAR(32) NOT NULL,
  13.     points INTEGER NOT NULL,
  14.     playedon DATE NOT NULL
  15. );
  16.  */
  17. public class ScoreServiceImpl implements ScoreService {
  18.     private static final String URL = "jdbc:postgresql://localhost/gamestudio";
  19.     private static final String LOGIN = "postgres";
  20.     private static final String PASSWORD = "postgres";
  21.  
  22.     private static final String INSERT_STMT =
  23.         "INSERT INTO score (ident, player, game, points, playedon) VALUES (?, ?, ?, ?, ?)";
  24.  
  25.     private static final String SELECT_STMT =
  26.         "SELECT ident, player, game, points, playedon FROM score WHERE game = ? ORDER BY points DESC LIMIT 10";
  27.  
  28.  
  29.  
  30.     @Override
  31.     public List<Score> getBestScoresForGame(String game) throws ScoreException {
  32.         List<Score> scores = new ArrayList<>();
  33.  
  34.         try(Connection connection = DriverManager.getConnection(URL, LOGIN, PASSWORD);
  35.             PreparedStatement ps = connection.prepareStatement(SELECT_STMT)) {
  36.             ps.setString(1, game);
  37.             try(ResultSet rs = ps.executeQuery()) {
  38.                 while(rs.next()) {
  39.                     Score score = new Score(rs.getInt(1), rs.getString(2), rs.getString(3),
  40.                             rs.getInt(4), rs.getDate(5));
  41.                     scores.add(score);
  42.                 }
  43.             }
  44.         } catch (SQLException e) {
  45.             throw new ScoreException("Error loading score", e);
  46.         }
  47.  
  48.         return scores;
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement