DBD::SQLite: Insert or Update - Question
While writing my question (howto: insert a new entry and if it exists already, update it) I found some answers in the Related Questions
:
$sql = "INSERT OR REPLACE INTO $table ( Id, Name, Rating ) VALUES( ?, ?, ? )";
$sth_rating = $dbh->prepare( $sql );
$sth_rating->execute( $id, $name, $rating );
.
$sql = "INSERT OR IGNORE INTO $table ( Id, Name, Rating ) VALUES ( ?,开发者_StackOverflow社区 ?, ? )";
$sth_rating = $dbh->prepare( $sql );
$sth_rating->execute( $id, $name, $rating );
$sql = "UPDATE $table SET Rating = ? WHERE Id = ?";
$sth_rating = $dbh->prepare( $sql );
$sth_rating->execute( $rating, $id );
Is the second method more safe then the first one?
The second method is less safe because it is non-atomic. In other words, it happens in more than one step. Consider two processes both updating the same data. Time is moving down.
Process 1 Process 2
INSERT OR IGNORE...
INSERT OR IGNORE...
UPDATE...
UPDATE...
Process 1 starts first, but Process 2 sneaks in and does its update between. Process 1 then blows right over Process 2's update.
This isn't so bad in this particular situation, both processes are going to blow over each other no matter what, but you can easily get yourself into trouble by extending your technique.
(Unless I misunderstood the question and what you want is an upsert)
精彩评论