【问题标题】:How to ignore a column in SQL updates如何忽略 SQL 更新中的列
【发布时间】:2018-09-27 13:55:03
【问题描述】:

我有一个程序可以查看用户模型,如果它们不为空,则将值添加到准备好的更新语句中,如下所示

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

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

【问题讨论】:

  • 一种方法是将语句构造为仅包含要更改的列。这将始终正常工作
  • 动态 SQL 有人吗?

标签: java mysql sql model prepared-statement


【解决方案1】:

添加参数,即使是 NULL 值。然后把update改成:

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

【讨论】:

  • @TheImpaler 。 . .您应该能够将NULL 作为参数值传入。 OP 专门要求这种类型的功能。
  • @The Impaler 如果您将? 值设置为用户模型读取的任何值,无论它们是否为空,此解决方案都有效。
  • @IsaacKrementsov 是的,只需确保更改原始逻辑以始终设置所有参数。未设置的参数可能会使您的代码崩溃。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-01
  • 2012-04-23
  • 1970-01-01
  • 2021-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多