UPDATE users SET age = 30 WHERE name = 'Alice'; UPDATE users SET age = 25 WHERE name = 'Bob'; UPDATE users SET age = 35 WHERE name = 'Charlie';
以上代码会导致并发性问题,因为多个更新语句可能会同时执行,导致数据错乱。
解决办法:
1、使用锁定
LOCK TABLES users WRITE; UPDATE users SET age = 30 WHERE name = 'Alice'; UPDATE users SET age = 25 WHERE name = 'Bob'; UPDATE users SET age = 35 WHERE name = 'Charlie'; UNLOCK TABLES;
2、使用事务
START TRANSACTION; UPDATE users SET age = 30 WHERE name = 'Alice'; UPDATE users SET age = 25 WHERE name = 'Bob'; UPDATE users SET age = 35 WHERE name = 'Charlie'; COMMIT;
一般使用事务,PHP操作:
$sqls=["START TRANSACTION"];//开启事务避免出错 for($datas as $d){ $sql="............"; array_push($sqls,$sql); } array_push($sqls,"COMMIT"); $sqls=implode(";",$sqls); $result=$pdo->query($sqls);
或者:
$db->query('START TRANSACTION'); $db->query('update member set money=money+'.$money.' where memberId='.$memberId); $db->query('insert into mem_log(money) values('.$money.')'); $db->query('commit');
或者:
try { // 开启事务 $pdo->beginTransaction(); // 执行一些SQL操作 $pdo->exec("INSERT INTO table1 (column1) VALUES ('value1')"); $pdo->exec("UPDATE table2 SET column2 = 'value2' WHERE id = 1"); // 提交事务 $pdo->commit(); } catch (Exception $e) { // 发生错误,回滚事务 $pdo->rollBack(); // 处理错误,例如打印错误信息 echo "Error: " . $e->getMessage(); }标签:insert,SET,users,age,UPDATE,update,mysql,WHERE,name From: https://www.cnblogs.com/prefertea/p/18168091