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 can ahange toString). Now, how can I show the returned Result Set in a tabular format ( I have no idea about structure of result set). Can anybody help me about this ?
You need to use ResultSet#getString to fetch the name . Now, each time you fetch one record, get the name field and add it to your list. Now, since you haven't given enough information about your DTO , so that part you need to find out, how to add this ArrayList to your DTO .
You can get the column count in a table using the getColumnCount() method of the ResultSetMetaData interface. On invoking, this method returns an integer representing the number of columns in the table in the current ResultSet object.
getString(String columnLabel) Retrieves the value of the designated column in the current row of this ResultSet object as a String in the Java programming language. Time. getTime(int columnIndex) Retrieves the value of the designated column in the current row of this ResultSet object as a java.
The ResultSet interface declares getter methods (for example, getBoolean and getLong ) for retrieving column values from the current row. You can retrieve values using either the index number of the column or the alias or name of the column. The column index is usually more efficient.
You can use Map<String, Object>
to represent a "dynamic" row, which is iterable in <c:forEach>
. 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<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();
ResultSetMetaData metaData = resultSet.getMetaData();
int columnCount = metaData.getColumnCount();
while (resultSet.next()) {
Map<String, Object> columns = new LinkedHashMap<String, Object>();
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:
<table>
<thead>
<tr>
<c:forEach items="${rows[0]}" var="column">
<td><c:out value="${column.key}" /></td>
</c:forEach>
</tr>
</thead>
<tbody>
<c:forEach items="${rows}" var="columns">
<tr>
<c:forEach items="${columns}" var="column">
<td><c:out value="${column.value}" /></td>
</c:forEach>
</tr>
</c:forEach>
</tbody>
</table>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With