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

2

6

I am using Anorm for database queries in my Play application. I went through some tutorials it is given that SQL(....).execute() returns Boolean if execution was succesful. I tested the method but it always returned false(don't know when it returns true:/ ). I also tried SQL(...).executeInsert() but there is not any 'auto-increment' column in the table, so the problem still exists. Please help me if there is any solution(any expanded version of the '.execute()' method or other) with anyone.

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.

Floret answered 12/10, 2013 at 10:17 Comment(0)
U
7

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.

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. (You could verify this pretty easily by trying to insert an entry with an id that youready have in the table)

Unlicensed answered 14/10, 2013 at 14:5 Comment(2)
Thanks Johanandren.. Now I actually understood the function. So, do I have to check for a successful insertion through Exception Handling? Isn't there any simple way ?Floret
Think of it as checking for exceptional behavior with exception handling :). Check out scala.util.Try, it might give you a nicer way of handling that exception than a try-catch.Unlicensed
A
-2

You should use 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.

Anode answered 12/10, 2013 at 10:22 Comment(1)
Sorry Ravi, but 'execute()' method returns only Boolean. It doesn't solves the problem.Floret

© 2022 - 2024 — McMap. All rights reserved.