如何创建Anorm查询以跳过更新DB(Scala)中的None值

如何创建Anorm查询以跳过更新DB(Scala)中的None值,scala,anorm,Scala,Anorm,我在Play+Scala应用程序(2.5.x,2.11.11)中使用了Anorm(2.5.1)。我经常遇到这样的问题:如果case类参数值为None,我不希望在sqldb中插入/更新该参数值。例如: case class EditableUser( user_pk: String, country: Option[String], country_phone_code: Option[Int], phonenumber: Option[String], e

我在Play+Scala应用程序(2.5.x,2.11.11)中使用了Anorm(2.5.1)。我经常遇到这样的问题:如果case类参数值为None,我不希望在sqldb中插入/更新该参数值。例如:

case class EditableUser(
    user_pk: String,
    country: Option[String],
    country_phone_code: Option[Int],
    phonenumber: Option[String],
    emailid: Option[String],
    format_all: Option[String]
)
....
val eUser: EditableUser = EditableUser("PK0001", None, None, None, Some("xyz@email.com"), Some("yes"))
...
    SQL"""
       update #$USR SET
       COUNTRY=${eUser.country},
       COUNTRY_PHONE_CODE=${eUser.country_phone_code},
       PHONENUMBER=${eUser.phonenumber},
       EMAILID=${emailid},
       FORMAT_ALL=${format_all}
       where (lower(USER_PK)=lower(${eUser.user_pk}))
    """.execute()

在这里,当值为None时,Anorm将在SQL DB中的相应列中插入“null”。相反,我希望以这样一种方式编写查询:Anorm跳过更新那些没有的值,即不覆盖。

您应该使用boundStatements/preparedStatement,并且在为查询设置值时,不要为没有的列设置值

比如说

SQL(
  """
select * from Country c 
join CountryLanguage l on l.CountryCode = c.Code 
where c.code = {countryCode};
  """
).on("countryCode" -> "FRA")
或者在您的情况下:

import play.api.db.DB
import anorm._

val stat = DB.withConnection(implicit c =>
  SQL("SELECT name, email FROM user WHERE id={id}").on("id" -> 42)
)
在编写查询时,检查要输入(x->something)的值是否为None如果很好,不要输入,因此不会更新None值

如果没有访问属性名称本身的能力(或库),那么仍然可以根据case类中存在的值动态构建update语句(如果在某些圆中有点笨拙):

case class Foo(name:String, age:Option[Int], heightCm:Option[Int])
...
def phrase(k:String,v:Option[Int]):String=if (v.isDefined) s", $k={$k}" else ""

def update(foo:Foo) : Either[String, Foo] = DB.withConnection { implicit c =>
  def stmt(foo:Foo) = "update foo set "+
    //-- non option fields
    "name={name}" +
    //-- option fields
    phrase("age", foo.age) +
    phrase("heightCm", foo.heightCm)

  SQL(stmt(foo))
    .on('name -> name, 'age -> age, 'heightCm -> heightCm)
    .executeUpdate()

实际提交的SQL中不存在的符号仍然可以在上的
中指定。还需要考虑其他数据类型。

您的回答没有回答我的问题。我正在寻找对Anorm查询的支持,目前还不可用。我还与其他人进行了检查。这允许在绑定之前准备语句,因此不准备不会绑定的字段参数让我知道是否需要删除答案