我应该如何在 Scala 和 Anorm 中使用 MayErr[IntegrityConstraintViolation,Int]?

2024-03-14

I use Anorm http://scala.playframework.org/documentation/scala-0.9.1/anorm进行数据库查询。当我做一个executeUpdate(),我应该如何进行正确的错误处理?它有返回类型MayErr[IntegrityConstraintViolation,Int],这是一个集合还是一个地图?

有一个example http://scala.playframework.org/documentation/scala-0.9.1/anorm#ExecutingSQLrequests,但我不明白应该如何处理返回值:

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!"
)

但我不知道我的错误处理代码应该是什么样子。有没有关于如何使用 type 的返回值的示例MayErr[IntegrityConstraintViolation,Int]?


看起来像MayErr正在包装Either。所以它既不是一个Map nor a Set,而是可以包含两个不同类型对象之一的对象。

看一眼这个问题 https://stackoverflow.com/questions/3496304/how-do-i-process-returned-either,您将看到一些处理 Either 对象的方法,在本例中该对象包含 IntegrityConstraintViolation 或 Int。参考http://scala.playframework.org/.../Scala$MayErr.html http://scala.playframework.org/documentation/api/scala-0.9.1/play/utils/Scala%24MayErr.html,看起来你可以通过引用 value 成员来获取 Either 对象e。似乎也有一个隐式转换可用,所以你可以只处理一个MayErr[IntegrityConstraintViolation,Int] as an Either[IntegrityConstraintViolation,Int]无需进一步的仪式。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

我应该如何在 Scala 和 Anorm 中使用 MayErr[IntegrityConstraintViolation,Int]? 的相关文章

随机推荐