I am trying to implement a counter in JDBC the method essentially increments a column value and returns the new column value, below is a snippet of my code i first perform a select .. for update to get the old value(also resulting in a row lock) then performing an update on that row. Am i right to assume that no other transaction can interfere with the value of the column val between the select .. for update then update.
//get connection here
con.setAutoCommit(false);
PreparedStatement statement = con.prepareStatement("SELECT val FROM atable WHERE id=? FOR UPDATE");
statement.setInt(1, id);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
oldVal = resultSet.getInt("val");
statement = con.prepareStatement("UPDATE atable SET val=" + oldVal + "+1 WHERE id=?");
statement.setInt(1, id);
int result = statement.executeUpdate();
if (result != 1) {
throw new SQLException("error message");
} else {
newVal = oldVal + 1;//could do another select statement to get the new value
statement.close();
}
} else {
throw new SQLException("error message");
}
resultSet.close();
con.commit();
con.setAutoCommit(true);
//close connection here
Thanks.