Как бороться с одновременными обновлениями в базах данных?

Каков общий способ иметь дело с одновременными обновлениями в базе данных SQL?

Рассмотрим простую схему SQL (ограничения и значения по умолчанию не показаны ..), например

create table credits (
  int id,
  int creds,
  int user_id
);

Цель состоит в том, чтобы хранить какие-то кредиты для пользователя, например, что-то вроде репутации stackoverflow.

Как бороться с одновременными обновлениями этой таблицы? Несколько вариантов:

update credits set creds= 150 where userid = 1;

In this case the application retreived the current value, calculated the new value(150) and performed an update. Which spells disaster if someone else does the same at the same time. I'm guessing wrapping the retreival of the current value and update in a transaction would solve that , e.g. Begin; select creds from credits where userid=1; do application logic to calculate new value, update credits set credits = 160 where userid = 1; end; In this case you could check if the new credit would be < 0 and just truncate it to 0 if negative credits make no sense.

update credits set creds = creds - 150 where userid=1;

This case wouldn't need to worry about concurrent updates as the DB takes care of the consistency problem, but has the flaw that creds would happily become negative, which might not make sense for some applications.

Итак, какой приемлемый метод для решения (довольно простой) проблемы, описанной выше, что делать, если db выдает ошибку?

Ответы на вопрос(9)

Ваш ответ на вопрос