我在 Play 应用程序中使用 Anorm 进行数据库查询。我浏览了一些教程,如果执行成功,SQL(....).execute()
返回Boolean
。我测试了该方法,但它总是返回 false
(不知道它什么时候返回 true:/)。我也尝试过 SQL(...).executeInsert() ,但表中没有任何“自动增量”列,因此问题仍然存在。如果有人有任何解决方案(“.execute()”方法的任何扩展版本或其他),请帮助我。
这是我的代码的一部分,由于意外返回而失败......
def addSuggestion(sessionId: BigInteger, suggestionId: BigInteger) = {
DB.withConnection { implicit c =>
if (!SQL("insert into user_suggestion_" + sessionId + " values (" + suggestionId + ",1,0,0)").execute()) {
SQL("update user_suggestion_" + sessionId + " set count=(count+1) where user_id=" + suggestionId).executeUpdate()
}
}
}
更新查询应仅在插入失败时运行(由于任何约束等)。还有其他功能/替代吗?请帮忙。提前致谢。
最佳答案
对 .execute() 的 Anorm 调用委托(delegate)给 jdbcPreparedStatement 类上的 .execute(),如果结果是 ResultSet,则返回 true;如果结果是“更新计数”或没有返回结果,则返回 false,因此它没有达到您的预期。
http://docs.oracle.com/javase/6/docs/api/java/sql/PreparedStatement.html#execute()
只要execute()调用没有抛出SqlException,我就期望插入成功。 (您可以通过尝试插入具有表中已有 ID 的条目来轻松验证这一点)
关于sql - 如何知道异常插入查询是否成功?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19333065/