How do I know if an insert request was successful in abnormal mode?

I use Anorm to query the database in the Play application. I looked through some tutorials in which SQL(....).execute() returns a Boolean if the execution was successful. I tested the method, but it always returned false (I don't know when it returns true: /). I also tried SQL(...).executeInsert() , but there is no "auto-increment" column in the table, so the problem still exists. Please help me if there is any solution (any extended version of the .execute () method or another) with someone.

Here is the part of my code that doesn't work 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 request should only be executed if the insert fails (due to any restrictions, etc.). Is there any other feature / alternative? Please help. Thank you in advance.

+6
source share
2 answers

An anonymous .execute () call delegates .execute () to the jdbc PreparedStatement class, which returns true if the result is a ResultSet and false if it is โ€œthe number of updatesโ€ or the result has not returned, so it does not do what you expected from him.

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

I expect the insertion to succeed until the call to execute () throws a SqlException. (You can check this quite easily by trying to insert a record with an identifier that you already have in the table)

+7
source

You should use the [Long] option

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

here the state variable is true or false.

-2
source

Source: https://habr.com/ru/post/955835/


All Articles