CS50 Lec7 - SqLite SameTime Update Error - Transaction


In a scenario, Bob and David clicked the like button on Instagram at the same time.
they all got the same value before it changed, like 1000.
So, after Bob clicked, and Added the like number, the result was 1001,
but same as David, got the previous value from the data base as 1000, so the result would not be 1002, but 1001.

How to resolve this problem?
We lock this process with transaction, the new command will not execute untill the last one complete (commit the transaction).

Transaction

db.execute("BEGIN TRANSACTION");
rows = db.execute("SELECT likes FROM posts WHERE id = ?", id);
like = row[0]["likes"];
db.execute("UPDATE POSTS SET likes = ? WHERE id = ?", likes + 1, id);
db.execute("COMMIT");
#SQL #sqllite #Transaction #cs50







你可能感興趣的文章

賦值後畫面卻沒更新?你聽過Vue.set()嗎

賦值後畫面卻沒更新?你聽過Vue.set()嗎

巨量資料 & 機器學習基礎教學

巨量資料 & 機器學習基礎教學

「Node.js」利用 .env 與環境變數隱藏敏感資料 by dotenv

「Node.js」利用 .env 與環境變數隱藏敏感資料 by dotenv






留言討論