[英]How should I use MayErr[IntegrityConstraintViolation,Int] in Scala and Anorm?
我使用Anorm进行数据库查询。 当我执行executeUpdate()
时,我应该如何进行正确的错误处理? 它具有返回类型MayErr[IntegrityConstraintViolation,Int]
,这是 Set 还是 Map?
有一个例子,但我不明白我应该如何处理返回值:
val result = SQL("delete from City where id = 99").executeUpdate().fold(
e => "Oops, there was an error" ,
c => c + " rows were updated!"
)
如何检查查询是否失败? (使用result
),如果查询成功,我如何获得受影响的行数?
目前我使用这段代码:
SQL(
"""
INSERT INTO users (firstname, lastname) VALUES ({firstname}, {lastname})
"""
).on("firstname" -> user.firstName, "lastname" -> user.lastName)
.executeUpdate().fold(
e => "Oops, therw was an error",
c => c + " rows were updated!"
)
但我不知道我的错误处理代码应该是什么样子。 有没有关于如何使用MayErr[IntegrityConstraintViolation,Int]
类型的返回值的示例?
看起来MayErr
正在包装Either
。 因此,它既不是Map
也不是Set
,而是可以包含两个不同类型对象之一的 object 。
看一下这个问题,您会看到一些处理 Either object 的方法,在本例中包含 IntegrityConstraintViolation 或 Int。 Referring to http://scala.playframework.org/.../Scala$MayErr.html , it looks like you can grab an Either object by referring to the value member e
. 似乎也有一个隐式转换可用,因此您可以将MayErr[IntegrityConstraintViolation,Int]
视为Either[IntegrityConstraintViolation,Int]
而无需进一步的仪式。
你显然可以做一个
val updateResult = ....executeUpdate()
val success = updateResult.fold(e => false, c => true)
看起来你也可以打电话
val success = updateResult.isRight
更一般地说,您可以使用
updateResult.e match {
case Left(error) => ... do something with error ...
case Right(updateCount) => ...do something with updateCount...
}
也许更熟悉 Play 的人会解释为什么 scala.Either 被包裹在 MayErr 中?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.