code_freak
code_freak

Reputation: 59

How to fetch entries/values from database to a jsp page one by one?

I have a table in Microsoft SQL server Management Studio with two columns title and data and each column has 10 enteries. I have a jsp page on which i want to display different database entries of the column title in different blocks. Now what code i should write that i get each entry in each block? On my jsp page i wrote:

<%  
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection cn = DriverManager.getConnection("jdbc:odbc:ablogs", "sa", "pretty");
Statement stmt = cn.createStatement();
ResultSet rs = stmt.executeQuery("select title from Postdata"); %>
 <table>
<tbody>
 <% while (rs.next()) {%>
<tr>
<td>
<%=rs.getString(1)%>
</td>
</tr>
<%}%>
</tbody>
</table>

through this code i get all entries at one time but i want to get values one by one in diffrent blocks.

Upvotes: 1

Views: 11300

Answers (1)

adarshr
adarshr

Reputation: 62613

Please ensure that you

  1. Use PreparedStatement instead of Statement
  2. Don't write extensive Java code inside JSPs (Strict no for database code!)

Assuming you'll change the above later (and if I have understood you correctly), you might want to do it like this:

ResultSet rs = stmt.executeQuery("select name, title, amount from Postdata"); %>
<table>
    <tbody>
    <% while (rs.next()) {%>
      <tr>
        <td>
          <%=rs.getString("name")%>
        </td>
        <td>
          <%=rs.getString("title")%>
        </td>
        <td>
          <%=rs.getString("amount")%>
        </td>
      </tr>
    <%}%>
</tbody>
</table>

Upvotes: 4

Related Questions