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 PrintOpinionsMain {
- private static final String SELECT_PRODUCT_QUERY = "SELECT id FROM products";
- private static final String SELECT_OPINIONS_BY_PRODUCT_QUERY =
- "SELECT * FROM opinions WHERE product_id = ?";
- public static void main(String[] args) {
- try (Connection connection = craeteConnection()) {
- printProductsIds(connection);
- int id = getUserInput();
- printOpinions(connection, id);
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- private static void printOpinions(Connection connection, int id) throws SQLException {
- try (PreparedStatement statement =
- connection.prepareStatement(SELECT_OPINIONS_BY_PRODUCT_QUERY);
- ) {
- statement.setInt(1, id);
- try (ResultSet resultSet = statement.executeQuery()) {
- while (resultSet.next()) {
- System.out.println("Opinions id : " + resultSet.getInt("id") + " description: " +
- resultSet.getString("description"));
- }
- }
- }
- }
- private static void printProductsIds(Connection connection) throws SQLException {
- try (PreparedStatement statement = connection.prepareStatement(SELECT_PRODUCT_QUERY);
- ResultSet resultSet = statement.executeQuery()) {
- while (resultSet.next()) {
- System.out.println("Product id : " + resultSet.getInt("id"));
- }
- }
- }
- private static Connection craeteConnection() throws SQLException {
- return DriverManager.getConnection("jdbc:mysql://localhost:3306/products_ex", "root", "root");
- }
- public static int getUserInput() {
- System.out.println("Wybierz id productu ");
- Scanner scanner = new Scanner(System.in);
- return scanner.nextInt();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement