Advertisement
Guest User

Untitled

a guest
Oct 20th, 2017
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.88 KB | None | 0 0
  1. package com.exam.fob;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.Date;
  5. import java.sql.DriverManager;
  6. import java.sql.PreparedStatement;
  7. import java.sql.ResultSet;
  8. import java.sql.SQLException;
  9. import java.sql.Statement;
  10. import java.util.Scanner;
  11.  
  12.  
  13. public class Main3 {
  14.    
  15.     public static final String selectMessagesSQL = "SELECT message FROM messages WHERE user_id = ?";
  16.    
  17.     public static final String selectOrdersSQL = "SELECT o.id AS 'order id', o.description, o.created, i.name, i.price " +
  18.             " FROM users u" +
  19.             " JOIN orders o ON u.id = o.user_id" +
  20.             " JOIN items_orders io ON o.id = io.order_id" +
  21.             " JOIN items i ON io.item_id = i.id" +
  22.             " WHERE u.id = ?";
  23.    
  24.     public static void main(String[] args) {
  25.  
  26.         int id;
  27.         System.out.print("Id użytkownika: ");
  28.         try(Scanner sc = new Scanner(System.in)) {
  29.             id = sc.nextInt();
  30.         }
  31.        
  32.         try (Connection conn = DriverManager.getConnection("jdbc:mysql://192.168.137.237:3306/exam_2?useSSL=false", "test", "test")) {
  33.            
  34.             System.out.println("Wiadomości użytkownika o ID: " + id);
  35.             PreparedStatement st = conn.prepareStatement(selectMessagesSQL);
  36.             st.setInt(1, id);
  37.             ResultSet rs = st.executeQuery();
  38.             while(rs.next()) {
  39.                 System.out.println(rs.getString("message"));
  40.             }
  41.            
  42.             st = conn.prepareStatement(selectOrdersSQL);
  43.             st.setInt(1, id);
  44.             rs = st.executeQuery();
  45.             while(rs.next()) {
  46.                 int orderId  = rs.getInt("order id");
  47.                 String desc = rs.getString("description");
  48.                 Date date = rs.getDate("created");
  49.                 String itemName = rs.getString("name");
  50.                 float price = rs.getFloat("price");
  51.                 System.out.printf("Id zamówienia; '%d', opis zamówienia: '%s' dnia '%s', przemiot: '%s' w cenie '%.2f' ", orderId, desc, date.toString(), itemName, price);
  52.                 System.out.println();
  53.             }
  54.            
  55.             st.close();
  56.         } catch (SQLException e) {
  57.             System.out.println(e.getMessage());
  58.         }
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement