Advertisement
Guest User

Untitled

a guest
Aug 3rd, 2017
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.24 KB | None | 0 0
  1. package mysql;
  2.  
  3. import java.sql.*;
  4. import java.util.Scanner;
  5.  
  6. public class DeleteFilmMain {
  7.  
  8. private static final String DELETE_MOVIE_BY_ID_QUERY =
  9. "DELETE FROM movies WHERE id = ?";
  10. private static final String GET_MOVIES_QUERY =
  11. "SELECT * FROM movies";
  12.  
  13. public static void main(String[] args) {
  14. String url = "jdbc:mysql://localhost:3306/cinemas_ex";
  15. Scanner scanner = new Scanner(System.in);
  16. try (Connection connection = getConnection(url)) {
  17. printMovies(connection);
  18. int id = scanner.nextInt();
  19. deleteMovie(connection, id);
  20. } catch (SQLException e) {
  21. e.printStackTrace();
  22. }
  23. }
  24.  
  25. private static final String MOVIE_PRINT_TEMPLATE =
  26. "Movie: id:%d name:%s, description:%s, rating:%f";
  27.  
  28. private static void printMovies(Connection connection) throws SQLException {
  29. try (PreparedStatement statement =
  30. connection.prepareStatement(GET_MOVIES_QUERY)) {
  31. try (ResultSet resultSet = statement.executeQuery()) {
  32. while (resultSet.next()) {
  33. int id = resultSet.getInt("id");
  34. double rating = resultSet.getDouble("rating");
  35. String name = resultSet.getString("name");
  36. String description = resultSet.getString("description");
  37. System.out.println(String.format(MOVIE_PRINT_TEMPLATE,
  38. id, name, description, rating));
  39. }
  40. }
  41. }
  42. }
  43.  
  44. private static void deleteMovie(Connection connection, int id) throws SQLException {
  45. try(PreparedStatement preparedStatement =
  46. connection.prepareStatement(DELETE_MOVIE_BY_ID_QUERY);
  47. ){
  48. preparedStatement.setInt(1, id);
  49. int deletedRecords = preparedStatement.executeUpdate();
  50. if(deletedRecords == 1){
  51. System.out.println("Record with id " + id + " was deleted");
  52. }else{
  53. System.out.println("Record was not deleted");
  54. }
  55. }
  56. }
  57.  
  58. private static Connection getConnection(String url) throws SQLException {
  59. return DriverManager.getConnection(url, "root", "root");
  60. }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement