Advertisement
Guest User

Untitled

a guest
May 18th, 2017
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.PreparedStatement;
  4. import java.sql.ResultSet;
  5. import java.sql.SQLException;
  6. // Movie 1
  7. //cinema 1
  8. //cinema 2
  9. //cinema 3
  10. //Movie 2
  11. //cinema 1
  12. //cinema 2
  13. //cinema 3
  14. public class Main2 {
  15.  
  16. private static final String GET_PRODUCTS = "SELECT * FROM products";
  17.  
  18. private static final String GET_PRODUCTS_IN_ORDERS = "SELECT * FROM products JOIN products_orders ON products.id = products_orders.products_id JOIN orders ON orders.id = products_orders.orders_id WHERE products_id = ?;";
  19.  
  20.  
  21.  
  22. public static void main(String[] args) throws SQLException {
  23. try (Connection connection = createConnection();
  24. PreparedStatement getOrdersStatement = connection.prepareStatement(GET_PRODUCTS);
  25. PreparedStatement getProductsStatement = connection.prepareStatement(GET_PRODUCTS_IN_ORDERS);
  26. ResultSet resultSet = getOrdersStatement.executeQuery();
  27. ) {
  28. while (resultSet.next()) {
  29. int id = resultSet.getInt("id");
  30. String name = resultSet.getString("name");
  31. System.out.println(String.format("Product id: %d, name: %s", id, name));
  32. printProductsForOrder(id, getProductsStatement);
  33. }
  34.  
  35. }
  36. }
  37. private static Connection createConnection() throws SQLException {
  38. return DriverManager.getConnection("jdbc:mysql://localhost:3306/products_ex",
  39. "root", "coderslab");
  40. }
  41. private static void printProductsForOrder(int id, PreparedStatement getProductsStatement) throws SQLException {
  42. getProductsStatement.setInt(1, id);
  43. try(ResultSet resultSet = getProductsStatement.executeQuery()){
  44. while (resultSet.next()){
  45. String description = resultSet.getString("description");
  46. int productId = resultSet.getInt("id");
  47. System.out.println(String.format("*\tOrder id: %d, description: %s", productId, description));
  48. }
  49. }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement