Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.sql.*;
- import java.util.*;
- public class Hello {
- public static void main(String[] args) throws Exception {
- Connection conn = null;
- Statement stmt = null;
- PreparedStatement ps = null;
- ResultSet rset = null;
- ResultSetMetaData md = null;
- Class.forName("org.postgresql.Driver");
- conn = DriverManager.getConnection("jdbc:postgresql://localhost/pg_demo");
- // conn.setAutoCommit(false);
- // stmt = conn.createStatement();
- // stmt.setFetchSize(1); // <----- Turn on stream ResultSet
- // rset = stmt.executeQuery("SELECT * from users;");
- rset = conn.getMetaData().getColumns(null, "public", "users", null);
- md = rset.getMetaData();
- // Close the connection
- conn.close();
- // Let's say I don't know what's in the database but I want to retrieve its content
- // Here there is no exception
- ArrayList<ArrayList<Object>> results = new ArrayList<>();
- while(rset.next()) {
- ArrayList<Object> row = new ArrayList<>();
- for (int i = 1; i <= md.getColumnCount(); i++){
- row.add(rset.getObject(i));
- }
- results.add(row);
- }
- // // Close the connection
- // conn.close();
- System.out.println(String.format("-> Result Size: %s", results.size()));
- // for Comdb2 -> Result Size: 0
- // for Postgres -> Result Size: 10
- // Print the results correctly for postgres but don't display anything for comdb2 (nothing in the list)
- for (int rowIndex = 0; rowIndex < results.size(); rowIndex++){
- ArrayList<Object> row = results.get(rowIndex);
- for (int columnIndex = 0; columnIndex < row.size(); columnIndex++){
- Object value = row.get(columnIndex);
- if (value != null)
- System.out.println(String.format("(Row %s, Column %s): %s", rowIndex, columnIndex, row.get(columnIndex).toString()));
- else
- System.out.println(String.format("(Row %s, Column %s): null", rowIndex, columnIndex));
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement