Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package blockPuzzle.service;
- import blockPuzzle.entity.Comment;
- import java.sql.*;
- import java.util.ArrayList;
- import java.util.List;
- public class CommentServiceJDBC implements CommentService{
- public static final String URL = "jdbc:postgresql://localhost/gamestudio2018";
- public static final String USER = "postgres";
- public static final String PASS = "postgres";
- public static final String INSERT =
- "INSERT INTO comment (game, username, comment_text, commented_on) VALUES (?, ?, ?, ?)";
- @Override
- public void addComment(Comment comment) throws CommentException {
- try {
- Class.forName("org.postgresql.Driver");
- }catch (ClassNotFoundException e) {
- System.err.println(e);
- System.exit(-1);
- }
- try (Connection c = DriverManager.getConnection(URL,USER,PASS)){
- try (PreparedStatement ps = c.prepareStatement(INSERT)){
- ps.setString(1,comment.getGame());
- ps.setString(2,comment.getUsername());
- ps.setString(3,comment.getComment_text());
- ps.setTimestamp(4,new Timestamp(comment.getCommentedOn().getTime()));
- }catch (SQLException e){
- throw new CommentException("Error saving comment",e);
- }
- }catch (SQLException e){
- throw new CommentException("Error connecting to database",e);
- }
- }
- public static final String SELECT =
- "SELECT game, username, comment_text, commented_on FROM comment " +
- "WHERE game = ?";
- @Override
- public List<Comment> getComments(String game) throws CommentException {
- List<Comment> comments = new ArrayList<>();
- try (Connection c = DriverManager.getConnection(URL,USER,PASS)){
- try (PreparedStatement ps = c.prepareStatement(SELECT)) {
- ps.setString(1,game);
- ResultSet rs = ps.executeQuery();
- while(rs.next()){
- Comment cm = new Comment(
- rs.getString(1),
- rs.getString(2),
- rs.getString(3),
- rs.getTimestamp(4)
- );
- comments.add(cm);
- }
- }catch (SQLException e) {
- throw new CommentException("Error saving comment",e);
- }
- }catch (SQLException e){
- throw new CommentException("Error connecting to database",e);
- }
- return comments;
- }
- public static void main(String[] args) throws Exception{
- Comment comment = new Comment("blockpuzzle","jakub","Vyborna hra nemam co dodat", new java.util.Date());
- CommentService commentService = new CommentServiceJDBC();
- commentService.addComment(comment);
- System.out.println(commentService.getComments("blockpuzzle"));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement