Advertisement
Guest User

Untitled

a guest
Aug 4th, 2017
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. package mysql;
  2.  
  3. import java.sql.*;
  4. import java.util.Scanner;
  5.  
  6. public class PrintOpinionsMain {
  7.  
  8. private static final String SELECT_PRODUCT_QUERY = "SELECT id FROM products";
  9. private static final String SELECT_OPINIONS_BY_PRODUCT_QUERY =
  10. "SELECT * FROM opinions WHERE product_id = ?";
  11.  
  12. public static void main(String[] args) {
  13. try (Connection connection = craeteConnection()) {
  14. printProductsIds(connection);
  15. int id = getUserInput();
  16. printOpinions(connection, id);
  17. } catch (SQLException e) {
  18. e.printStackTrace();
  19. }
  20. }
  21.  
  22. private static void printOpinions(Connection connection, int id) throws SQLException {
  23. try (PreparedStatement statement =
  24. connection.prepareStatement(SELECT_OPINIONS_BY_PRODUCT_QUERY);
  25. ) {
  26. statement.setInt(1, id);
  27. try (ResultSet resultSet = statement.executeQuery()) {
  28. while (resultSet.next()) {
  29. System.out.println("Opinions id : " + resultSet.getInt("id") + " description: " +
  30. resultSet.getString("description"));
  31. }
  32. }
  33. }
  34. }
  35.  
  36. private static void printProductsIds(Connection connection) throws SQLException {
  37. try (PreparedStatement statement = connection.prepareStatement(SELECT_PRODUCT_QUERY);
  38. ResultSet resultSet = statement.executeQuery()) {
  39. while (resultSet.next()) {
  40. System.out.println("Product id : " + resultSet.getInt("id"));
  41. }
  42. }
  43. }
  44.  
  45. private static Connection craeteConnection() throws SQLException {
  46. return DriverManager.getConnection("jdbc:mysql://localhost:3306/products_ex", "root", "root");
  47. }
  48.  
  49. public static int getUserInput() {
  50. System.out.println("Wybierz id productu ");
  51. Scanner scanner = new Scanner(System.in);
  52. return scanner.nextInt();
  53. }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement