简体   繁体   English

如何知道插入查询是否在anorm中成功完成?

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

I am using Anorm for database queries in my Play application. 我在Play应用程序中使用Anorm进行数据库查询。 I went through some tutorials it is given that SQL(....).execute() returns Boolean if execution was succesful. 我经历了一些教程,给出了SQL(....).execute()如果执行成功则返回Boolean I tested the method but it always returned false (don't know when it returns true:/ ). 我测试了该方法,但它总是返回false (不知道它什么时候返回true:/)。 I also tried SQL(...).executeInsert() but there is not any 'auto-increment' column in the table, so the problem still exists. 我也尝试过SQL(...).executeInsert()但是表中没有任何“自动增量”列,所以问题仍然存在。 Please help me if there is any solution(any expanded version of the '.execute()' method or other) with anyone. 如果有任何解决方案(任何扩展版本的'.execute()'方法或其他),请帮助我。

Here is a part of my code which is failing due to unexpected return... 这是我的代码的一部分,由于意外返回而失败...

    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()
          }
        }
      }

The update query should run only when the insertion fails(due to any constraint etc.). 更新查询应仅在插入失败时运行(由于任何约束等)。 Is there any other function/alternative? 还有其他功能/替代方案吗? Please help. 请帮忙。 Thanks in advance. 提前致谢。

The Anorm call to .execute() delegates to .execute() on the jdbc PreparedStatement class, which returns true if the result is a ResultSet and false if it is an "update count" or no result came back, so it does not do what you expected it to. Anorm调用.execute()委托给jdbc PreparedStatement类上的.execute(),如果结果是ResultSet则返回true,如果是“更新计数”则返回false,或者没有结果返回,所以它不会你期望它。

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

I would expect the insert to be successful as long as the execute() call did not throw a SqlException. 只要execute()调用没有抛出SqlException,我希望插入成功。 (You could verify this pretty easily by trying to insert an entry with an id that youready have in the table) (您可以通过尝试插入具有表中已有ID的条目来轻松验证这一点)

You should use Option[Long] 你应该使用Option [Long]

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

here status variable has true or false values. 这里status变量有true或false值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM