Home » excel » java – Fetch an entire row with jdbc as a List

java – Fetch an entire row with jdbc as a List

Posted by: admin April 23, 2020 Leave a comment

Questions:

I need to fetch data from multiple tables and export into excel sheet for each table. I don’t want to use the getXXX() method as there are large number of columns and I don’t know the data type of each column. I need to fetch an entire row and store in the result in List.
I fetched each column using getObject() and also the class type using MetaData.getColumnClassName().

For example

Object val = resultSet.getObject(i);

I try to cast this val to its actual type using getColumnClassName() but it gives me an error while casting.

Can anyone please help me.

public class Row {

public Map<Object, Class> row;
public static Map<String, Class> TYPE;

static {
    TYPE = new HashMap<String, Class>();
    TYPE.put("INTEGER", Integer.class);
    TYPE.put("NUMERIC", BigDecimal.class);
    TYPE.put("DOUBLE", Double.class);
    TYPE.put("VARCHAR2", String.class);

}

public Row() {
    row = new HashMap<Object, Class>();
}

public <t> void add(t data) {
    row.put(data, data.getClass());
}

public void add(Object data, String sqlType) {
    add((Row.TYPE.get(sqlType)) data);
}

public static void formTable(ResultSet rs, List<Row> table) throws SQLException {
    if(rs == null)
        return;
    ResultSetMetaData rsmd = rs.getMetaData();
    int colCt = rsmd.getColumnCount();
    while(rs.next()) {
        Row row = new Row();
        for(int i = 0; i < colCt; i++) {
            row.add(rs.getObject(i), rsmd.getColumnTypeName(i));
        }
        table.add(row);
    }
}
public static void main(String[] args) {

}

}

How to&Answers:

Try this code:

Connection connection = DriverManager.getConnection("URL", "USERNAME", "PASSWORD");
PreparedStatement statement = connection.prepareStatement("select * from table");
ResultSet resultSet = statement.executeQuery();

if (resultSet != null) {
    while (resultSet.next()) {
        ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
        for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {

            int type = resultSetMetaData.getColumnType(i);
            if (type == Types.VARCHAR || type == Types.CHAR) {
                 System.out.println(resultSet.getString(i));
            } else {
                 System.out.println(resultSet.getLong(i));
            }
        }

         System.out.println("-----------");
    }
}

You should extend it with other datatypes.

Answer:

Step 1: get the metadata

ResultSetMetaData rsmd;
rsmd = rs.getMetaData();
int numColumns = rsmd.getColumnCount();
int[] columnsType = new int[numColumns + 1];
columnsType[0] = 0;
for (int i = 1; i <= numColumns; i++) 
    columnsType[i] = rsmd.getColumnType(i);

Step 2: fetch a row at a time from the result set and check the data type

String s;
Object o;
while (rs.next()) {
    for (int i = 1; i <= numColumns; i++) {
        if (columnsType[i] == java.sql.Types.NUMERIC || columnsType[i] == java.sql.Types.CHAR || columnsType[i] == java.sql.Types.VARCHAR) {
            s = rs.getString(i);
        } else if (columnsType[i] == java.sql.Types.NVARCHAR) {
            s = rs.getNString(i);
        } else if (columnsType[i] == java.sql.Types.BOOLEAN) {
            // TODO
        } else if (columnsType[i] == java.sql.Types.FLOAT || columnsType[i] == java.sql.Types.DOUBLE) {
            // TODO
        } else if (columnsType[i] == java.sql.Types.TINYINT || columnsType[i] == java.sql.Types.SMALLINT || columnsType[i] == java.sql.Types.INTEGER || columnsType[i] == java.sql.Types.BIGINT) {
            // TODO
        } else if (columnsType[i] == java.sql.Types.DATE || columnsType[i] == java.sql.Types.TIMESTAMP) {
            // TODO
        } else {
            o = rs.getObject(i);
        }
    }
}

Step 3: fill the blanks and add the exception handling

Step 4: write to Excel (inside the loop)

Answer:

public class EXECUTEQUERY implements Module {

    private static final DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private String userId;
    String result = "";
    String resp = "";
    static int count = 1;
    private final Logger log = Logger.getLogger("EXECUTEQUERY");

    private void dbg(String msg) {
        log.info(userId + ":" + msg);
    }
    private void dbg(Exception ex) {
        log.info(ex.getMessage());
        ex.printStackTrace();
    }
    private void uDbg(String msg) {
        log.info(userId + " :" + msg);
    }
    private void uDbg(Exception ex) {
        uDbg(ex.getMessage());
        ex.printStackTrace();
    }
    public String main(UserContext userContext, String reqXml) {
        dbg("Query recieved is " + reqXml);

        String resp;
        userId = userContext.getUserId();

        if (userContext.getAction().equals("EXECUTEQUERY")) {
            if (reqXml == null || reqXml.equals("")) {
                result = "!Please Enter the query";
            } else {
                result = getQueryResult(userContext, reqXml);
            }
        }
        return result;
    }
    /***
     * 
     * for adding search record in backend created by @shyamlal yadav
     * @param userContext
     * @param reqXml 
     */
    public void addQueryLog(UserContext userContext, String reqXml) {
         dbg("inside addQueryLog methos request is " + reqXml);
        userId = userContext.getUserId();

        dbg( userId +"this user is selecting value from screen");

        System.out.println("recieve request  is " + reqXml);
        PreparedStatement pStmt = null;
        Connection eodConn = null;
        dbg("addQueryLog recieved for log  " + reqXml);

        Date date = new Date();
        java.sql.Date sqlDate = new java.sql.Date( date.getTime()); 
        eodConn = EODConnectionFactory.getInstance().getFCConnectionFromPool();

        try {
            pStmt = eodConn.prepareStatement("insert into EOD_QRY_EXEC_LOG (QRY_EXEC_TIMESTAMP, QRY_TEXT,OPERATOR_ID)\n"
                    + " values (?,?,?)");
            pStmt.setTimestamp(1, new java.sql.Timestamp(System.currentTimeMillis()));
            pStmt.setString(2, reqXml);
            pStmt.setString(3, userId);
            pStmt.executeQuery();
        } catch (SQLException ex)  {
            dbg("Exception is " + ex);
            return;
        }
        EODConnectionFactory.returnFCConnectionToPool(eodConn);
        return;
    }

    /*
     This method returns query excecuted table data with separators.
     @Shaymlal, 
     */
    public String getQueryResult(UserContext userContext, String reqXml) {
        String field_value = "";
        String lsitofquery = "";
        String resultlist = "";
        dbg("Inside getQueryResult method");
        Connection eodConn = null;
        Statement stmt = null;
        eodConn = EODConnectionFactory.getInstance().getFCConnectionFromPool();
        try {
            stmt = eodConn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
            ResultSet rs = stmt.executeQuery(reqXml);
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            dbg("Total no of column is:" + columnCount);

            int rsCount = 1;
            while (rs.next()) {
                if (rsCount == 1) {
                    for (int i = 1; i <= columnCount; i++) {
                        resultlist += "~" + rsmd.getColumnName(i);
                    }
                }
                for (int i = 1; i <= columnCount; i++) {
                    field_value += "~" + rs.getString(i);
                }
                field_value = field_value + "~<>";
                lsitofquery = resultlist + "~>" + field_value;
                rsCount = rsCount + 1;
            }
        } catch (Exception ex) {
            dbg("Exception is " + ex);
            return "!Exception  invalid query: " + ex;
        }
        EODConnectionFactory.returnFCConnectionToPool(eodConn);

        // return rowCount > 0 ? lsitofquery+">" : "!Table is Empty" ;
        addQueryLog(userContext,reqXml);
        return lsitofquery + ">";
    }
}