Advertisement
Guest User

Untitled

a guest
Aug 3rd, 2017
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.34 KB | None | 0 0
  1. package mysql;
  2.  
  3. import java.sql.*;
  4. import java.util.Scanner;
  5.  
  6. public class TicketsMain {
  7.  
  8. /**
  9. * 1. Pobierz z bazy listę biletów i wyświetl na konsoli.
  10. 2. Pobierz od użytkownika identyfikator biletu z konsoli.
  11. 3. Pobierz z konsloli ilość sprzedanych biletów.
  12. 4. Zmodyfikuj odpowiedni wiersz w bazie danych.
  13. */
  14.  
  15. private static final String GET_TICKET_QUERY =
  16. "SELECT * FROM tickets";
  17. private static final String UPDATE_TICKET_QUERY =
  18. "UPDATE tickets SET quantity = quantity + ? WHERE id = ?";
  19.  
  20. public static void main(String[] args){
  21. Scanner scanner = new Scanner(System.in);
  22. try(Connection connection = getConnection()){
  23. while (true) {
  24. printTickets(connection);
  25. int id = scanner.nextInt();
  26. int quantity = scanner.nextInt();
  27. updateTicket(connection, quantity, id);
  28. }
  29. } catch (SQLException e) {
  30. e.printStackTrace();
  31. }
  32. }
  33.  
  34. private static void updateTicket(Connection connection, int quantity, int id) throws SQLException {
  35. try( PreparedStatement statement =
  36. connection.prepareStatement(UPDATE_TICKET_QUERY)){
  37. statement.setInt(1, quantity);
  38. statement.setInt(2, id);
  39. int i = statement.executeUpdate();
  40. if(i == 1){
  41. System.out.println("Ticket " + id + " was updated");
  42. }else{
  43. System.out.println("Ticket " + id + " was not updated");
  44. }
  45. }
  46. }
  47.  
  48. private static void printTickets(Connection connection) throws SQLException {
  49. try( PreparedStatement statement =
  50. connection.prepareStatement(GET_TICKET_QUERY);
  51. ResultSet resultSet = statement.executeQuery()) {
  52. while (resultSet.next()) {
  53. int id = resultSet.getInt("id");
  54. int quantity = resultSet.getInt("quantity");
  55. double price = resultSet.getDouble("price");
  56. System.out.println("id: " + id + " quantity: " +
  57. quantity + " price: " + price);
  58. }
  59. }
  60. }
  61.  
  62. private static Connection getConnection() throws SQLException {
  63. return DriverManager.getConnection("jdbc:mysql://localhost:3306/cinemas_ex"
  64. ,"root", "root");
  65. }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement