简体   繁体   中英

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM