Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package mysql;
- import java.sql.*;
- import java.util.Scanner;
- public class DeleteFilmMain {
- private static final String DELETE_MOVIE_BY_ID_QUERY =
- "DELETE FROM movies WHERE id = ?";
- private static final String GET_MOVIES_QUERY =
- "SELECT * FROM movies";
- public static void main(String[] args) {
- String url = "jdbc:mysql://localhost:3306/cinemas_ex";
- Scanner scanner = new Scanner(System.in);
- try (Connection connection = getConnection(url)) {
- printMovies(connection);
- int id = scanner.nextInt();
- deleteMovie(connection, id);
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- private static final String MOVIE_PRINT_TEMPLATE =
- "Movie: id:%d name:%s, description:%s, rating:%f";
- private static void printMovies(Connection connection) throws SQLException {
- try (PreparedStatement statement =
- connection.prepareStatement(GET_MOVIES_QUERY)) {
- try (ResultSet resultSet = statement.executeQuery()) {
- while (resultSet.next()) {
- int id = resultSet.getInt("id");
- double rating = resultSet.getDouble("rating");
- String name = resultSet.getString("name");
- String description = resultSet.getString("description");
- System.out.println(String.format(MOVIE_PRINT_TEMPLATE,
- id, name, description, rating));
- }
- }
- }
- }
- private static void deleteMovie(Connection connection, int id) throws SQLException {
- try(PreparedStatement preparedStatement =
- connection.prepareStatement(DELETE_MOVIE_BY_ID_QUERY);
- ){
- preparedStatement.setInt(1, id);
- int deletedRecords = preparedStatement.executeUpdate();
- if(deletedRecords == 1){
- System.out.println("Record with id " + id + " was deleted");
- }else{
- System.out.println("Record was not deleted");
- }
- }
- }
- private static Connection getConnection(String url) throws SQLException {
- return DriverManager.getConnection(url, "root", "root");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement