Java type incompatibility

Asked

Viewed 66 times

0

String query = "INSERT INTO codigos(Nome,Codigo) VALUES( '"+nome+"','" +codigo+ "')";

 rs = st.executeUpdate(query);

rs is a resulset, st is a statement, an error appears to say that there is an incompatibility of types needs the type java.sql.Resulset and says he finds a int. I don’t understand why

  • According to the api documentation, the method executeUpdate() returns a int

  • 2

    Read that.

  • As @Victorstafusa recommended if there are parameters in the query prefer Preparedstatement (including it makes the escape of special characters for you, thing that concatenation does not)

1 answer

2


When you do an Insert, the return is not a Resultset, but an integer containing the amount of lines affected by the executed transaction.

To recover something via Resultset using executeUpdate would be to pick up the auto-increment ID, Now this has no reason. To test do so:

st = Conn.prepareStatement(queryString, PreparedStatement.RETURN_GENERATED_KEYS);
// [...] Parametros [...]
int K = st.executeUpdate();

if(K > 0) {
   rs = st.getGeneratedKeys();

   if (rs.next()) {
      SeuObjeto.setID(rs.getInt(1));
   }
}
  • To use getGeneratedKeys() you have to warn in building your Insert using Statement.RETURN_GENERATED_KEYS

  • Yes I forgot to quote. But it’s fact. Thank you for the warning. Adjusted response!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.