本文介绍了如何在Scala和Anorm中使用MayErr [IntegrityConstraintViolation,Int]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用进行数据库查询。当我执行 executeUpdate()时,应该如何进行正确的错误处理?它有返回类型 MayErr [IntegrityConstraintViolation,Int] ,这是一套还是一张地图?

I use Anorm to do database queries. When I do an executeUpdate(), how should I do proper error handling? it has return type MayErr[IntegrityConstraintViolation,Int], is this a Set or a Map?

,但我不明白我应该如何处理返回值:

There is an example, but I don't understand how I should handle the return value:

val result = SQL("delete from City where id = 99").executeUpdate().fold( 
    e => "Oops, there was an error" , 
    c => c + " rows were updated!"
)

如何检查查询失败? (使用 result ),如果查询成功,我该如何获得受影响的行数?

How do I check if the query failed? (using result), and how do I get the numer of affected rows if the query was successful?

我使用这段代码的时候:

At the moment I use this code:

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] 的返回值的示例?

But I don't know how my error-handling code should look like. Is there any example on how to use the return value of type MayErr[IntegrityConstraintViolation,Int]?

推荐答案

你显然可以做一个

val updateResult = ....executeUpdate()
val success = updateResult.fold(e => false, c => true)

看起来你也可以调用

val success = updateResult.isRight

更一般地说,您可以使用

More generally, you can access the wrapped Either with

updateResult.e match {
    case Left(error) => ... do something with error ...
    case Right(updateCount) => ...do something with updateCount...
}

也许有人比较熟悉Play会解释为什么scala.En被包裹在MayErr?

Maybe someone more familiar with Play would explain why scala.Either is wrapped in MayErr?

这篇关于如何在Scala和Anorm中使用MayErr [IntegrityConstraintViolation,Int]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 14:24