java 如何将数据库中的条目/值一一提取到jsp页面?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7359930/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to fetch entries/values from database to a jsp page one by one?
提问by code_freak
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:
我在 Microsoft SQL Server Management Studio 中有一个表,其中包含两列标题和数据,每列有 10 个条目。我有一个 jsp 页面,我想在该页面上显示不同块中列标题的不同数据库条目。现在我应该写什么代码来获取每个块中的每个条目?在我的jsp页面上,我写道:
<%
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.
通过这段代码,我一次获得了所有条目,但我想在不同的块中一一获得值。
回答by adarshr
Please ensure that you
请确保您
- Use PreparedStatementinstead of Statement
- Don't write extensive Java code inside JSPs (Strict no for database code!)
- 使用PreparedStatement而不是 Statement
- 不要在 JSP 中编写大量的 Java 代码(对数据库代码严格禁止!)
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>