mysql更新方法不能正常工作

jgovgodb  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(661)

我为mysql数据库编写了以下更新方法。

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>

在editservlet中,我编写了以下代码。

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    String rid=request.getParameter("id");  
    int id=Integer.parseInt(rid);  
    String fname =request.getParameter("fname");  
    String lname=request.getParameter("lname");  

    User u =new User();  
    u.setName(fname);  
    u.setLname(lname); 
    u.setId(id);
    UserM um = new UserM(); 
    int up_status = um.update(u);  

    if(up_status > 0) {

        request.getRequestDispatcher("/GetUserInfo").forward(request, response); 
    } else {  
        request.setAttribute("errorMessage", "Could not change info");
        request.getRequestDispatcher("/GetUserInfo").forward(request, response);  
    }

}

在我运行代码并更新数据之后,每次都会显示错误消息。我的代码的实现有什么问题吗?

gstyhher

gstyhher1#

在此代码中

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);
mzaanser

mzaanser2#

问题出在我的sql语句上。我忘了名字后面有个逗号。它应该是:“update users set f\u name=?,l\u name=?其中id=?“

相关问题