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 TicketsMain {
- /**
- * 1. Pobierz z bazy listę biletów i wyświetl na konsoli.
- 2. Pobierz od użytkownika identyfikator biletu z konsoli.
- 3. Pobierz z konsloli ilość sprzedanych biletów.
- 4. Zmodyfikuj odpowiedni wiersz w bazie danych.
- */
- private static final String GET_TICKET_QUERY =
- "SELECT * FROM tickets";
- private static final String UPDATE_TICKET_QUERY =
- "UPDATE tickets SET quantity = quantity + ? WHERE id = ?";
- public static void main(String[] args){
- Scanner scanner = new Scanner(System.in);
- try(Connection connection = getConnection()){
- while (true) {
- printTickets(connection);
- int id = scanner.nextInt();
- int quantity = scanner.nextInt();
- updateTicket(connection, quantity, id);
- }
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- private static void updateTicket(Connection connection, int quantity, int id) throws SQLException {
- try( PreparedStatement statement =
- connection.prepareStatement(UPDATE_TICKET_QUERY)){
- statement.setInt(1, quantity);
- statement.setInt(2, id);
- int i = statement.executeUpdate();
- if(i == 1){
- System.out.println("Ticket " + id + " was updated");
- }else{
- System.out.println("Ticket " + id + " was not updated");
- }
- }
- }
- private static void printTickets(Connection connection) throws SQLException {
- try( PreparedStatement statement =
- connection.prepareStatement(GET_TICKET_QUERY);
- ResultSet resultSet = statement.executeQuery()) {
- while (resultSet.next()) {
- int id = resultSet.getInt("id");
- int quantity = resultSet.getInt("quantity");
- double price = resultSet.getDouble("price");
- System.out.println("id: " + id + " quantity: " +
- quantity + " price: " + price);
- }
- }
- }
- private static Connection getConnection() throws SQLException {
- return DriverManager.getConnection("jdbc:mysql://localhost:3306/cinemas_ex"
- ,"root", "root");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement