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.
You can check the @@ROWCOUNT right after insert. If it's more than 0, then the insert succeeded. Also, if @@ERROR = 0 after insert, it was successful. No, check it in T-SQL although if the insert will result in error, most likely the error will be propagated into the client.
To check if your INSERT was successful, you can use mysqli_affected_rows() . Returns the number of rows affected by the last INSERT, UPDATE, REPLACE or DELETE query. And check for errors against your query and for PHP.
Anorm is a simple data access layer that uses plain SQL to interact with the database and provides an API to parse and transform the resulting datasets.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With