Check whether a record is updated in postgres data

2019-09-16 04:52发布

问题:

How can I know from java whether a record is updated when update query is called. I had tried the return type int from executeUpdate() but it will show 1 whenever the query is executed. That is if the record is changed or not it will return value > 1. If there is an opportunity for trigger in postgresql for calling a java method() would be helpful for this. Please help.

回答1:

If you need to know whether a row's data was changed as a result of the update, you would need to pass the parameters to the WHERE clause, making a statement such as UPDATE foo SET bar = $1, baz = $2 WHERE bar <> $1 AND baz <> $2 AND id = $3. Example is assuming you wish to update two columns of a single row based on id.

After that the only way the WHERE clause will match is if there is an actual update to do, and you can use the return value to check if an update occurred or not.

Another possibility is to refactor your code so that you don't need to bother about it, but you will need to explain your use case further for that.



回答2:

executeUpdate(Query) will return number of rows updated

int rows = statement.executeUpdate("Your_query");
System.out.println("number of rows updated "+rows);

rows will be 0 if nothing updated