Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package sk.tuke.kp.bricksbreaker.Service;
- import sk.tuke.kp.bricksbreaker.Entity.FavouriteGame;
- import java.sql.*;
- import java.sql.Date;
- import java.util.*;
- /**
- * Created by jakubcervenak on 16/03/16.
- */
- public class FavouriteServiceImpl implements FavouriteService {
- private static final String URL = "jdbc:postgresql://localhost/codermakac";
- private static final String LOGIN = "postgres";
- private static final String PASSWORD = "pomaranc";
- private static final String INSERT_STMT =
- "INSERT INTO favourites (player, game, date) VALUES (?, ?, ? )";
- private static final String SELECT_STMT =
- "SELECT player, game, date FROM favourites WHERE player = ? ORDER BY player ASC";
- @Override
- public void addFavourite(FavouriteGame favouriteGame) throws FavouriteException {
- try(Connection connection = DriverManager.getConnection(URL, LOGIN, PASSWORD);
- PreparedStatement ps = connection.prepareStatement(INSERT_STMT)) {
- ps.setString(1, favouriteGame.getPlayer());
- ps.setString(2, favouriteGame.getGame());
- ps.setDate(3, new java.sql.Date(favouriteGame.getDate().getTime()));
- ps.executeUpdate();
- } catch (SQLException e) {
- throw new FavouriteException("Error saving favourites", e);
- }
- }
- @Override
- public List<FavouriteGame> getFavouriteGame(String player) throws FavouriteException {
- List<FavouriteGame> favourites = new ArrayList<>();
- try(Connection connection = DriverManager.getConnection(URL, LOGIN, PASSWORD);
- PreparedStatement ps = connection.prepareStatement(SELECT_STMT)) {
- ps.setString(1, player);
- try(ResultSet rs = ps.executeQuery()) {
- while(rs.next()) {
- FavouriteGame favouriteGame = new FavouriteGame(rs.getString(1), rs.getString(2),
- rs.getDate(3));
- favourites.add(favouriteGame);
- }
- }
- } catch (SQLException e) {
- throw new FavouriteException("Error loading favourites", e);
- }
- return favourites;
- }
- public static void main(String[] args) throws FavouriteException {
- FavouriteGame favourite = new FavouriteGame("jacky", "bricks",new java.util.Date());
- FavouriteService favouriteService = new FavouriteServiceImpl();
- favouriteService.addFavourite(favourite);
- System.out.println(favouriteService.getFavouriteGame("jacky"));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement