Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- // Movie 1
- //cinema 1
- //cinema 2
- //cinema 3
- //Movie 2
- //cinema 1
- //cinema 2
- //cinema 3
- public class Main2 {
- private static final String GET_PRODUCTS = "SELECT * FROM products";
- 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 = ?;";
- public static void main(String[] args) throws SQLException {
- try (Connection connection = createConnection();
- PreparedStatement getOrdersStatement = connection.prepareStatement(GET_PRODUCTS);
- PreparedStatement getProductsStatement = connection.prepareStatement(GET_PRODUCTS_IN_ORDERS);
- ResultSet resultSet = getOrdersStatement.executeQuery();
- ) {
- while (resultSet.next()) {
- int id = resultSet.getInt("id");
- String name = resultSet.getString("name");
- System.out.println(String.format("Product id: %d, name: %s", id, name));
- printProductsForOrder(id, getProductsStatement);
- }
- }
- }
- private static Connection createConnection() throws SQLException {
- return DriverManager.getConnection("jdbc:mysql://localhost:3306/products_ex",
- "root", "coderslab");
- }
- private static void printProductsForOrder(int id, PreparedStatement getProductsStatement) throws SQLException {
- getProductsStatement.setInt(1, id);
- try(ResultSet resultSet = getProductsStatement.executeQuery()){
- while (resultSet.next()){
- String description = resultSet.getString("description");
- int productId = resultSet.getInt("id");
- System.out.println(String.format("*\tOrder id: %d, description: %s", productId, description));
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement