准备好的语句executeUpdate不能与update语句一起工作



我使用以下代码使用postgres的更新查询更改密码。

@POST
@Path("/changepassword")
@Consumes(MediaType.APPLICATION_JSON)
public String changePassword(String msg) {
    JSONObject jsonObject = new JSONObject(msg);
    String songString = null;
    String query = null;
    PreparedStatement stmt = null;
    try {
        if (UserManagement.authMail(jsonObject.getString("mail"))) {
            songString = Utilities.constructJSON("welcome", true);
            Connection connection = MyResource.getConnection();
            query = "UPDATE users SET password = '" + jsonObject.getString("password") + "' WHERE mail = ' "
                    + jsonObject.getString("mail") + "'";
            stmt = connection.prepareStatement(query);
            stmt.executeUpdate();
            songString = Utilities.constructJSON("Password reset successfull", true);
        } else {
            songString = Utilities.constructJSON("Please check your mail address", true);
        }
    } catch (Exception ex) {
        songString = Utilities.constructJSON("" + query + ex, true);
    }
    return songString;
}

不影响数据库。为什么会这样呢?我的连接处于自动提交模式,但仍然没有更新。我怎样才能解决这个问题呢?

这可能对你有帮助:

Connection connection = MyResource.getConnection();
query = "UPDATE users SET password = ? WHERE mail = ?";
stmt = connection.prepareStatement(query);
stmt.setString(1,jsonObject.getString("password"));
stmt.setString(2,jsonObject.getString("mail"));
stmt.executeUpdate();

并且确保jsonObject.getString("password")jsonObject.getString("mail")得到一些值

查询在mail参数处包含一个额外的空白,这可能导致查询不返回任何行。

UPDATE users SET password = 'Password' WHERE mail = ' mailadress'

尝试删除空格,看看这是否会影响数据库。

最好使用Keval Pithva提供的答案中提到的预处理语句

创建连接时:

con.setAutoCommit(true);

这对你有帮助。

最新更新