[英]How to create Anorm query to skip updating None values in DB (Scala)
我在Play + Scala應用程序(2.5.x,2.11.11)中使用了Anorm(2.5.1)。 我經常遇到這個問題,如果case類參數值為None,我不希望在SQL DB中插入/更新該參數值。 例如:
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跳過更新那些值為None(即不覆蓋)的值。
您應該使用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)
)
在編寫查詢時,您檢查要放在on(x-> something)上的值是否不為None(如果可以的話)請不要輸入,因此不會更新為none的值。
如果沒有能力(或庫)本身訪問屬性名稱,則即使在某些情況下有些笨拙,仍然有可能根據case類中存在的值動態地構建更新語句:
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()
仍可以在on
指定實際提交的SQL中不存在的符號。 還需要迎合其他數據類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.