Advertisement
Guest User

Untitled

a guest
May 18th, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.98 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.  
  7. public class Main {
  8. //Order 1
  9. //product 1
  10. //product 2
  11. //Order 2
  12. //product 1
  13. //product 2
  14. private static final String GET_ORDERS_QUERY =
  15. "SELECT * FROM orders";
  16. private static final String GET_PRODUCTS_FOR_ORDER_QUERY =
  17. "SELECT * FROM products p, products_orders po " +
  18. "WHERE p.id = po.products_id AND ? = po.orders_id";
  19.  
  20. public static void main(String[] args) throws SQLException {
  21. try (Connection connection = createConnection();
  22. PreparedStatement getOrdersStatement = connection.prepareStatement(GET_ORDERS_QUERY);
  23. PreparedStatement getProductsStatement = connection.prepareStatement(GET_PRODUCTS_FOR_ORDER_QUERY);
  24. ResultSet resultSet = getOrdersStatement.executeQuery();
  25. ) {
  26. while (resultSet.next()) {
  27. int id = resultSet.getInt("id");
  28. String description = resultSet.getString("description");
  29. System.out.println(String.format("Order id: %d, description: %s", id, description));
  30. printProductsForOrder(id, getProductsStatement);
  31. }
  32.  
  33. }
  34. }
  35.  
  36. private static void printProductsForOrder(int id, PreparedStatement getProductsStatement) throws SQLException {
  37. getProductsStatement.setInt(1, id);
  38. try(ResultSet resultSet = getProductsStatement.executeQuery()){
  39. while (resultSet.next()){
  40. String name = resultSet.getString("name");
  41. int productId = resultSet.getInt("id");
  42. System.out.println(String.format("*\tProduct id: %d, name: %s", productId, name));
  43. }
  44. }
  45. }
  46.  
  47. private static Connection createConnection() throws SQLException {
  48. return DriverManager.getConnection("jdbc:mysql://localhost:3306/products_ex",
  49. "root", "coderslab");
  50. }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement