Guest User

Untitled

a guest
Oct 31st, 2016
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. import java.sql.*;
  5.  
  6. public class GetMinionNames {
  7. private static final String URL = "jdbc:mysql://localhost:3306/minions_db";
  8. private static final String USER = "root";
  9. private static final String PASSWORD = "1234";
  10.  
  11. public static void main(String[] args) throws IOException {
  12. BufferedReader bfr = new BufferedReader(new InputStreamReader(System.in));
  13.  
  14. int villainID = Integer.parseInt(bfr.readLine());
  15.  
  16. String query = "SELECT v.name, m.name, m.age FROM minions AS m" +
  17. "INNER JOIN villains AS v" +
  18. "ON v.id = ?" +
  19. "WHERE m.id IN (SELECT vm.minion_id FROM villains_minions AS vm" +
  20. "WHERE vm.villain_id = ?)";
  21.  
  22. try (Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
  23. PreparedStatement prepStatement = connection.prepareStatement(query)){
  24.  
  25. prepStatement.setInt(1, villainID);
  26. prepStatement.setInt(2, villainID);
  27. ResultSet resultSet = prepStatement.executeQuery();
  28.  
  29. if (resultSet.next()){
  30. String villainName = resultSet.getString("vil_name");
  31. System.out.printf("Villain: %s\n", villainName);
  32. } else {
  33. System.out.printf("No villain with ID %d exists in the database.\n", villainID);
  34. }
  35.  
  36. int number = 1;
  37.  
  38. while (resultSet.next()){
  39. String minionName = resultSet.getString("name");
  40.  
  41. if (minionName == null){
  42. System.out.printf("<no minions>");
  43. }
  44. int minAge = resultSet.getInt("age");
  45. System.out.printf("%d. %s %s", number, minionName, minAge);
  46. number++;
  47. }
  48. } catch (SQLException e) {
  49. e.printStackTrace();
  50. }
  51. }
  52. }
Add Comment
Please, Sign In to add comment