如何忽略SQL更新中的列

时间:2018-09-27 13:55:03

标签: java mysql sql model prepared-statement

我有一个程序可以检查User模型,并在值不为null时将值添加到准备好的更新语句中,如下所示:

    PreparedStatement pst = conn.prepareStatement("UPDATE users SET name=?,email=?,pwd=?,avatar=?,sts=?,bio=?,country=? WHERE uuid=?");
    if(this.name != null) pst.setString(1, this.name);
    if(this.email != null) pst.setString(2, this.email);
    if(this.password != null) pst.setString(3, this.password);
    if(this.avatar != null) pst.setString(4, this.avatar);
    if(this.status != null) pst.setString(5, this.status);
    if(this.bio != null) pst.setString(6, this.bio);
    if(this.country != null) pst.setString(7, this.country);
    pst.setString(6, this.id);

我面临的问题是,在准备好的语句中不能有未定义的字段。我可以将不想更改的字段设置为等于什么?

1 个答案:

答案 0 :(得分:1)

即使具有NULL值也要添加参数。然后将update更改为:

UPDATE users
    SET name = coalesce(?, name),
       email = coalesce(?, email),
       . . .
   WHERE uuid = ?;