How to know that if a Insert query was succesfull in anorm?
我在Play应用程序中使用Anorm进行数据库查询。我遍历了一些教程,假设执行成功,则
这是我的代码的一部分,由于意外返回而失败...
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。