iam使用while循环从数据库中检索数据,如下所示以表格格式输出数据,以及while循环中包含select列的列,现在select选项的选项是; (待定和清除),我想选择使用它来更新相应的数据库表,但问题是,当我按下更新按钮时,它会更新所有值而不是特定的selected.plz帮助。
html代码
<tr>
<td width=50><div align="center"><%=datez%></div></td>
<td width=50><div align="center"><%=cashrecid%></div></td>
<td width=50><div align="center"><%=fname%></div></td>
<td width=50><div align="center"><%=lname%></div></td>
<td width=50><div align="center"><%=cashout%></div></td>
<td width=50><div align="center"><%=purpose%></div></td>
<td width=50><div align="center"><%=project%></div></td>
<td width=50><div align="center">
<select name="select" size="1" id="select">
<option value="pending">pending</option>
<option value="cleared">cleared</option>
</select>
</div></td>
</tr>
jsp代码
<%@ page import="java.sql.*" %>
<%@ page import="java.util.*" %>
<%! public int cashrecid; %>
<%
String uname=(String)session.getAttribute("theName");
String status=request.getParameter("select");
Connection con1=DriverManager.getConnection("jdbc:odbc:pettyz","sa","pass@word");
PreparedStatement stmt1=con1.prepareStatement("select cashrecid from cashrequisitions where status='pending' ");
ResultSet rs1=stmt1.executeQuery();
while(rs1.next()) {
cashrecid=rs1.getInt(1);
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:pettyz","sa","pass@word");
PreparedStatement stmt=con.prepareStatement("update cashrequisitions set status=? where cashrecid=?");
stmt.setString(1,status);
stmt.setInt(2,cashrecid);
stmt.executeUpdate();
}
rs1.close();
stmt1.close();
con1.close();
%>
答案 0 :(得分:1)
我不明白实际的问题/要求。
但至少我可以看到以下内容:您的第一个SQL查询是从DB中检索状态为“pending”的所有 cashrequisitions。您的第二个查询会将获取的现金取消的所有的状态更新为所选值。因此,如果您选择“待定”,实际上什么都不会改变。但是如果你选择“清除”,有效的一切都会被设置为“清除”。您将没有剩下一行,状态为“待定”。 uname
变量进一步悬挂了一点。
在第一次查询中,您不需要uname
吗?毕竟功能要求是什么?您是否只想更改特定uname
的状态,该preparedStatement = connection.prepareStatement("UPDATE cashrequisitions set status=? where uname=?");
preparedStatement.setString(1, status);
preparedStatement.setString(2, uname);
也是cashrequisitions表的一列?如果是这样,您需要将两个 SQL查询替换为:
status
此查询将有效地将指定uname
的所有cashrequisition的{{1}}更新为指定的状态值。如果您在SQL中遇到困难(看起来如此),我可以向您推荐这个基本的SQL tutorial。
那就是说,你的代码有点......呃.. 不寻常的。您通常在Java类中编写Java代码,而不是在JSP文件中编写Java代码。忽略那些老式的90年代教程。强烈建议不要使用scriptlet。编写JDBC代码的方式也远非高效且对资源泄漏非常敏感。为了了解如何以正确的方式完成基本操作,您可能会发现this article很有用。