关于sql:如何知道在anorm中插入查询是否成功?

How to know that if a Insert query was succesfull in anorm?

我在Play应用程序中使用Anorm进行数据库查询。我遍历了一些教程,假设执行成功,则SQL(....).execute()返回Boolean。我测试了该方法,但它始终返回false(不知道何时返回true:/)。我也尝试了SQL(...).executeInsert(),但是表中没有任何"自动增量"列,因此问题仍然存在。如果有人与任何人有任何解决方案('.execute()'方法的任何扩展版本或其他),请帮助我。

这是我的代码的一部分,由于意外返回而失败...

1
2
3
4
5
6
7
    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调用将委托给jdbc PreparedStatement类上的.execute(),如果结果为ResultSet,则返回true;如果结果为" update count "或没有结果返回,则返回false,因此它没有达到您的预期。

http://docs.oracle.com/javase/6/docs/api/java/sql/PreparedStatement.html#execute()

我希望插入能够成功,只要execute()调用未引发SqlException。 (您可以通过尝试在表中插入具有您已经拥有的ID的条目来轻松验证这一点)


您应该使用Option [Long]

1
val STATUS:OPTION[Long]=SQL("insert into user_suggestion_" + sessionId +" values (" + suggestionId +",1,0,0)").execute()

此处状态变量的值为true或false。