Advertisement
Guest User

Untitled

a guest
Nov 12th, 2017
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 KB | None | 0 0
  1. package hello_world;
  2. import java.sql.*;
  3. import java.util.ArrayList;
  4.  
  5. public class sqlStuff {
  6. /** This method returns the number of columns in a query. */
  7. private static int getColCount(ResultSet rs) {
  8. int x = 1;
  9. for (;x < 10; x++) {
  10. try {
  11. System.out.println(rs.getObject(x));
  12. } catch (SQLException e) {
  13. //e.printStackTrace();
  14. //System.out.println("Found an error at: " + x);
  15. break;
  16. }
  17. }
  18. //System.out.println("Stopping at: " + (x - 1));
  19. return x - 1;
  20. }
  21.  
  22. /** This method returns an ArrayList of objects that can be printed, each object representing one element of the returned query. */
  23. private static ArrayList<Object> showObj(ResultSet rs, int columnCount) {
  24. System.out.println(columnCount);
  25. ArrayList<Object> rowEntries = new ArrayList<Object>();
  26. for (int x = 1; x <= columnCount; x++) {
  27. try {
  28. System.out.println(rs.getObject(x));
  29. rowEntries.add(rs.getObject(x));
  30. } catch (SQLException e) {
  31. //DOES NOTHING ON ERROR
  32. }
  33. }
  34. System.out.println(rowEntries);
  35. return rowEntries;
  36. }
  37.  
  38. /** This method shows the results of a query. */
  39. public static void showResults() {
  40. try{
  41. Class.forName("com.mysql.jdbc.Driver");
  42. Connection con=DriverManager.getConnection(
  43. "jdbc:mysql://localhost:3306/employees","root","PASSWORD");
  44. Statement stmt=con.createStatement();
  45. ResultSet rs = stmt.executeQuery("select t.title, max(s.salary) from titles t join salaries s on t.emp_no = s.emp_no group by t.title;");
  46. int columnCount = 0;
  47. while(rs.next())
  48. columnCount = getColCount(rs);
  49. //columnCount = getColCount(rs);
  50. //System.out.println(columnCount);
  51. //System.out.println(getColCount(rs));
  52. System.out.println(showObj(rs,columnCount));
  53. con.close();
  54. }
  55. catch(Exception e){
  56. System.out.println(e);
  57. }
  58. }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement