java中的MySQL更新方法无法正常工作
我已经为我的MySQL数据库编写了以下更新方法java中的MySQL更新方法无法正常工作,java,html,mysql,jsp,servlets,Java,Html,Mysql,Jsp,Servlets,我已经为我的MySQL数据库编写了以下更新方法 public int update(User u) { int status = 0; Connection connection = null; PreparedStatement stm = null; try { connection = ConnectionConfiguration.getConnection(); stm = connection.prepareStat
public int update(User u) {
int status = 0;
Connection connection = null;
PreparedStatement stm = null;
try {
connection = ConnectionConfiguration.getConnection();
stm = connection.prepareStatement("UPDATE users SET f_name=?
l_name=? WHERE id=?");
stm.setString(1, u.getName());
stm.setString(2, u.getLname());
stm.setInt(3, u.getId());
status = stm.executeUpdate();
} catch(Exception e) {
e.printStackTrace();
} finally {
if(stm != null) {
try {
stm.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
} return status;
}
然后我更新JSP类中的数据,如下所示:
<% int id =Integer.parseInt(request.getParameter("Userid"));
UserM um = new UserM();
User u = new User();
u = um.select(id);
%>
<form method="GET" action="EditServlet">
<input type="hidden" name="id" value="<%=u.getId()%>">
Name:<input type="text" name="fname" value="<%=u.getName()%>"><br>
Last name:<input type="text" name="lname" value="<%=u.getLname()%>"><br>
<input type="submit" value="Edit">
</form>
在我运行代码并更新数据之后,每次都会显示错误消息。我的代码的实现有什么问题吗?在这段代码中
User u =new User();
u.setName(fname);
u.setLname(lname);
您没有设置User::id
的值,因此当您在update(User u)
中使用它时,该值将为零
改为
User u =new User();
u.setName(fname);
u.setLname(lname);
u.setId (id);
问题在于我的SQL语句。我忘了f_名字后面有个逗号。应该是:
“UPDATE users SET f_name=?,l_name=?WHERE id=?”它每次都会显示错误消息-该错误是什么?同样在
update
什么是res
?错误消息是我用request.setAttribute指定的消息(“errorMessage”,“无法更改信息”);这就是它的全部功能。它不会更新任何数据否,它不会显示任何异常无关:用于消除所有古怪(和不稳定)的close()
逻辑。还有,为什么要在JSP中执行select
部分?您确定检索到了记录吗?为什么在发布表单时要执行Get
?是时候做些调试了。对不起,弄错了。我的代码里确实有。我一定是忘了写在这里了。在这种情况下,您的数据库中似乎没有一个id为的用户。我确实检查了我的数据库,有一个id为的用户,所以我不知道问题出在哪里。您问题的第1版有这个,
-我们如何才能成功回答?这是因为当我在这里写它时,我把它放在了原来的代码中,但我忘记了它
User u =new User();
u.setName(fname);
u.setLname(lname);
u.setId (id);