How to get a value from an executeUpdate OR update in java?

3.1k views Asked by At

Im trying to get some returning data from an postgresql update. The "update" works well in the DB script, but in java I'm having some issues: the code stucks while executing the query.

I'm trying with "PreparedStatament ps", "ResultSet rs=ps.executeQuery" and "if(rs.next)" to get the data from the "returning" in the query, but it appears that the code didnt get in there, because it stuck exactly in the "ps.executeQuery".

Here's more or less what I'm trying to do:

String cVal="";
ps=myConn.prepareStatement("UPDATE someTable SET aValue=? WHERE bValue=? 
returning Cvalue");
ps.setInt(1,"aNewValue");
ps.setInt(2,"aID");
rs=ps.executeQuery();
if (rs.next()){
  cVal=rs.GetString("Cvalue");
  return true;
}else{
  return false;
}

I'm trying to set the values of "RETURNING" to some variables. There are 4 results that I want to set.

2

There are 2 answers

2
Sambit On BEST ANSWER

Since you are trying to update, in case of PreparedStatement, you have to use executeUpdate() method.

To know more details about methods in Statement and PreparedStatment, check below the

https://docs.oracle.com/javase/8/docs/api/java/sql/PreparedStatement.html#executeUpdate--

You can refer below an example. https://www.mkyong.com/jdbc/jdbc-preparestatement-example-update-a-record/

1
angelR On

First execute the update statement with ps.executeUpdate (), which returns the integer 0 or 1. The value indicates whether the update statement has executed or not. After that, execute the select query to get the updated data.