How to map a ResultSet with unknown amount of columns to a List and display it in a HTML table?

后端 未结 2 860
野的像风
野的像风 2020-12-01 10:12

I have created a Database Application using Netbeans, GlassFish and JavaDB. Now my controller Servlet code executes some dynamic SQL queries and get back a Result Set (or I

2条回答
  •  悲哀的现实
    2020-12-01 10:34

    You can use Map to represent a "dynamic" row, which is iterable in . You can use ResultSetMetaData to collect information about the columns such as the column count and the column labels.

    So, this mapping should do:

    List> rows = new ArrayList>();
    ResultSetMetaData metaData = resultSet.getMetaData();
    int columnCount = metaData.getColumnCount();
    
    while (resultSet.next()) {
        Map columns = new LinkedHashMap();
    
        for (int i = 1; i <= columnCount; i++) {
            columns.put(metaData.getColumnLabel(i), resultSet.getObject(i));
        }
    
        rows.add(columns);
    }
    

    You can display it in JSP as follows:

    
            
          
              

提交回复
热议问题