Mozbi
Mozbi

Reputation: 1479

jdbc combine 2 sql update statements

Is there a way to combine statements 1 and 2 into 1 query? Thanks.

String statement1 = "UPDATE thing SET status = ? WHERE id = ?";
String statement2 = "UPDATE thing SET error_message = ? WHERE id = ?";

PreparedStatement preparedStatement = connection.prepareStatement(statement1);
preparedStatement.setInt(1,status);
preparedStatement.setInt(2, id);
connection.prepareStatement(statement2);
preparedStatement.setInt(1,error_message);
preparedStatement.setInt(2, id);

Upvotes: 0

Views: 177

Answers (2)

Ankur Lathi
Ankur Lathi

Reputation: 7836

Do it like this:

    String statement1 = "UPDATE thing SET status = ? ,error_message = ? WHERE id = ?";

    PreparedStatement preparedStatement = connection.prepareStatement(statement1);
    preparedStatement.setInt(1,status);
    preparedStatement.setInt(2,error_message);
    preparedStatement.setInt(3, id);
    preparedStatement.executeUpdate();

Upvotes: 0

sanbhat
sanbhat

Reputation: 17622

Looks like you are trying to set 2 columns of same table for an ID. You can change the query like

"UPDATE thing SET status = ? ,error_message = ? WHERE id = ?"

Further more, if the 2 update statements are updating different tables, you can execute both in same transaction. In this way, you can be sure that the commit will take place if both the statement successfully updates the table. Check the example here

Upvotes: 5

Related Questions