在数据库中更新了相同的值

时间:2018-03-25 16:56:53

标签: java mysql jsp

我正在编写代码来重置用户密码。但是当我登录并尝试更改密码时,新密码会在存储在数据库中的每条记录中更新,即输入的新密码将更新为所有记录的新密码。我试图编辑更新查询,但我的语法错误,我该如何解决?

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

</body>
</html>
<%@page import="java.sql.*"%>
<%@page import="java.io.*"%>
<%
    String OldPassword = request.getParameter("OldPassword");
    String Newpass = request.getParameter("newpassword");
    String conpass = request.getParameter("conpassword");


    Connection con = null;
    Statement st = null;
    String pass = "";
    int id = 0;
    try {
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/form";
        con = DriverManager.getConnection(url, "root", "");
        st = con.createStatement();
        ResultSet rs = st.executeQuery("select * from login where password= '"+ OldPassword + "'");
        if (rs.next()) {
            pass = rs.getString("password");
        }
        if(Newpass.equals(conpass))
        {
            if (pass.equals(OldPassword)) {
                st = con.createStatement();
                int i = st.executeUpdate("update login set password='"+ Newpass + "'");
                out.println("Password changed successfully");
                st.close();
                con.close();
            } else {
                out.println("Old Password doesn't match");
            }
/*}else{
out.println("new password and confirm new password is not matching");
}*/
        }
    } catch (Exception e) {
        out.println(e);
    }
%>

2 个答案:

答案 0 :(得分:1)

您还需要在查询中添加一个where子句,该子句将密码更新限制为仅限该用户。

您可以使用用户的ID更新密码。

您可以在

中找到用户ID
if (rs.next()) {
    pass = rs.getString("password");
    id = rs.getString("id");
}

然后你更新查询将是:

st.executeUpdate("update login set password='" + Newpass + "' where id='" + id + "'");

答案 1 :(得分:0)

Try to use PreparedStatement because it is fast and more secure Check this for further Information and try not to marge all the code in one line use preparedStatement.setString(value) this is also prevents you from attacks of SQL Injection and executes more effectively..;

int i = st.executeUpdate("update login set password= ?");
              st.setString(newPass);
                out.println("Password changed successfully");
                st.close();
                con.close();
            } else {
                out.println("Old Password doesn't match");
            }