servlet dynamically add/drop a column from table

aauser
aauser used Ask the Experts™
on
Hi,
  I can add or drop a column in my table,
but how can I make it so that it dynamically
update on how to display the total column
from the table:

ex: Let says currently have a table with three columns;
if I add one more column, how can I write a loop
so that it prints out four columns; and if I delete
one column, how can I write a loop so that i prints
out 2 columns with headings ,headings can be the name of the colums, (when I select to query database).


String col1 = "Name";
String col2 = "phone";
String col3 = "email";

out.println("<TD>"+col1+"<TD>"+col2+"<TD>"+col3");
while (rset.next ()) {
             out.println("<TR>");
             for (int i=1;i<=3;i++) {
                out.println("<TD>"+rset.getString
                 (i));
             }


====
html file:
Column Name:<INPUT type=text name="newcolumn">



thanks in advance:


Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Commented:
You might try using ResultSetMetaData.  For example, the following code prints a list of the column names returned by a query.

ResultSet rs = stmt.executeQuery("SELECT a,b FROM c");
ResultSetMetaData rsmd = rs.getMetaData();
for (int i = 0; i < rsmd.getColumnCount(); i++){
System.out.println(rsmd.getColumnLabel(i));
}
You might try rsmd.getColumnName(i), if getColumnLabel(i) doesn't work properly.
Mick BarryJava Developer
Top Expert 2010

Commented:
You need to maintain a list of required columns in the session, and use this list when constructing query and resulting table.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial