Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically create row and column of table in jsp page

I am trying to retrieve data from database into table. But data must be loaded dynamically.

How to dynamically create row and column I don't know? If it will be only row to create then I will do it easily but I also want to create column dynamically on page so that's why I am confused how to perform it?

My JSP code :

<table width="59%" border="1">
    <%
        MySql1 o = new MySql1();
        o.connect();
        ResultSet r;
        int counter=1;
        String q = "select * from category_master;";
        r = o.getdata(q);
        while(r.next())
        {
            %>
                <tr>
                     <td><%= r.getString(1)%></td>                                      
                </tr>
            <% 
        }
    %>
</table>

Right now I am displaying first column in <td> but if the user don't know how many columns are going to be retrieved then what to do ? In select query I have used * so I am confused for taking <td>. I want to all dynamic because suppose I will pass table name also dynamically using any textbox or url.

Here MySql1 is one class file that has method to perform operation. connect() is used to connect with db, and getdata() is used to retrieve data of query passed as argument and return type of getdata() method is Resultset.

So that's why I want all dynamic, but I don't know how to do that.

like image 499
Java Curious ღ Avatar asked Sep 28 '13 12:09

Java Curious ღ


1 Answers

try this code:

<table width="59%" border="1">
    <%
        MySql1 o = new MySql1();
        o.connect();
        ResultSet r;
        int counter=1;
        String q = "select * from category_master;";
        r = o.getdata(q);
        ResultSetMetaData metaData = r.getMetaData();
        while(r.next())
        {
            %>
                <tr>
                 <%
                 for(int i = 1; i<=metaData.getColumnCount();i++)
                    { %>
                     <td>
                     <%= r.getString(i)%>
                     </td>
                <% 
                    }
                %>                   
                </tr>
            <% 
        }
    %>
</table>
like image 112
Gaurav Singla Avatar answered Nov 13 '22 21:11

Gaurav Singla