update(){# res表示更新语句影响的行数int res =0;# 无限循环更新for(;;){# 查询出当前的version, 假设结果为v1SELECTversionFROM user whereuid=1;# 更新,设置额外条件version=v1,并同时更新version字段 res =UPDATE user SETname=maxwell, version=v1+1WHEREuid=1ANDversion=v1;# 说明更新成功if(res ==1){break; } }}
tryUpdate(inttimes){# res表示在最多times次尝试后,最终是否更新成功boolean res = false;for(x intimes){# 查询出当前的version, 假设结果为v1SELECTversionFROM user whereuid=1;# 更新,设置额外条件version=v1,并同时更新version字段int i =UPDATE user SETname=maxwell, version=v1+1WHEREuid=1ANDversion=v1;if(i ==1 ){ res = true;break; } }return res;}
update(){int res =0;for(;;){SELECTtimeFROM user whereuid=1; # 假设结果为time1 res =UPDATE user SETname=maxwell, time=CURRENT_TIME WHEREuid=1ANDtime=time1;if(res ==1){break; } }}tryUpdate(inttimes){boolean res = false;for(x intimes){SELECTtimeFROM user whereuid=1; # 假设结果为time1int i =UPDATE user SETname=maxwell, time=CURRENT_TIME WHEREuid=1ANDtime=time1;if(i ==1 ){ res = true;break; } }return res;}
updateDisk(){UPDATEdiskSETsize= ? WHERE id =1; updateHost();}updateHost(){intsize=SELECTSUM(size) FROMdiskWHERE host_id =1FORUPDATE; UPDATE host SET disk_size=sizeWHERE id=1;}