Search code examples
jdbcdb2zos

jdbc-db2 - extract full record


I tried to pull the data from a DB2 table. I would like to know whether there is a way to print the whole record from ResultSet without specifying the individual column names.

My Code:

import java.sql.*;

            public class Ftp {
                public static void main(String[] args) {
                    String url = "jdbc:db2://mvshost:4456/SQA_SYSTEM";
                    String user = "xxxxx";
                    String password = "yyyyyy";
                    Connection con;
                    PreparedStatement stmt;
                    ResultSet rs;
                    try {
                        Class.forName("com.ibm.db2.jcc.DB2Driver");
                        con = DriverManager.getConnection(url, user, password);
                        con.setAutoCommit(false);
                        stmt = con.prepareStatement("SELECT EMP FROM IDATDMK.GREEN");
                        rs = stmt.executeQuery();
                        while (rs.next()) {
                            String EMP = rs.getString("EMP");
                            System.out.println("EMP from DB2 = " + EMP);                    
                        }
                        rs.close();
                        stmt.close();
                        con.commit();
                        con.close();

                    }
                    catch (Exception e) {
                      System.out.println("Exception: " + e);
                      }
                    }
                }
            }

If I write my query as Select * from IDATDMK.GREEN, how can I print the whole record in while loop without specifying the individual column names. I have 80+ columns in the table.


Solution

  • ResultSetMetaData rsmd = rs.getMetaData();
    int columnsNumber = rsmd.getColumnCount();
    
    while(rs.next(){
    for (int i = 1; i <= columnsNumber; i++) {
           if (i > 1) System.out.print("\n");
           String columnValue = rs.getString(i);
           System.out.print(columnValue) }}