我使用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
,而是一个可以包含两个不同类型对象之一的对象。
看看这个问题,你会发现一些处理"任一"对象的方法,在本例中,该对象包含IntegrityConstraintViolation或Inthttp://scala.playframework.org/.../Scala$MayErr.html,看起来可以通过引用值成员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的原因。两者都裹着MayErr?