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.
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)