Advertisement
Guest User

Untitled

a guest
Jul 3rd, 2017
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. import java.sql.*;
  2. import java.util.*;
  3.  
  4. public class Hello {
  5. public static void main(String[] args) throws Exception {
  6. Connection conn = null;
  7. Statement stmt = null;
  8. PreparedStatement ps = null;
  9. ResultSet rset = null;
  10. ResultSetMetaData md = null;
  11. Class.forName("org.postgresql.Driver");
  12. conn = DriverManager.getConnection("jdbc:postgresql://localhost/pg_demo");
  13. // conn.setAutoCommit(false);
  14. // stmt = conn.createStatement();
  15. // stmt.setFetchSize(1); // <----- Turn on stream ResultSet
  16. // rset = stmt.executeQuery("SELECT * from users;");
  17. rset = conn.getMetaData().getColumns(null, "public", "users", null);
  18. md = rset.getMetaData();
  19.  
  20. // Close the connection
  21. conn.close();
  22.  
  23. // Let's say I don't know what's in the database but I want to retrieve its content
  24. // Here there is no exception
  25. ArrayList<ArrayList<Object>> results = new ArrayList<>();
  26. while(rset.next()) {
  27. ArrayList<Object> row = new ArrayList<>();
  28. for (int i = 1; i <= md.getColumnCount(); i++){
  29. row.add(rset.getObject(i));
  30. }
  31. results.add(row);
  32. }
  33.  
  34. // // Close the connection
  35. // conn.close();
  36.  
  37. System.out.println(String.format("-> Result Size: %s", results.size()));
  38. // for Comdb2 -> Result Size: 0
  39. // for Postgres -> Result Size: 10
  40.  
  41. // Print the results correctly for postgres but don't display anything for comdb2 (nothing in the list)
  42. for (int rowIndex = 0; rowIndex < results.size(); rowIndex++){
  43. ArrayList<Object> row = results.get(rowIndex);
  44. for (int columnIndex = 0; columnIndex < row.size(); columnIndex++){
  45. Object value = row.get(columnIndex);
  46. if (value != null)
  47. System.out.println(String.format("(Row %s, Column %s): %s", rowIndex, columnIndex, row.get(columnIndex).toString()));
  48. else
  49. System.out.println(String.format("(Row %s, Column %s): null", rowIndex, columnIndex));
  50. }
  51. }
  52. }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement