暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

mysql 1z0-909每日一题8

原创 山丘smith 2025-06-27
626

Examine these statements which execute successfully:

try { $connect->beginTransaction(); $result = $connect->exec("INSERT INTO band(song) VALUES('Here comes the sun')"); $result = $connect->exec("SAVEPOINT addsong;"); } catch(PDOException $ex){ echo "Query error: " . $ex->getMessage() . "\n"; } try{ $connect->rollBack(); $result = $connect->exec("DELETE FROM band;"); $result = $connect->exec("INSERT INTO band(song) VALUES('Here comes the sun')"); } catch (PDOException $ex){ echo "Rollback error: " . $ex->getMessage() . "\n"; }

The statements executed without exception. Which two are true?
A) No transaction commits.
B) One row is inserted into band.
C) Two transactions commit.
D) No row is inserted into band.
E) The transaction is rolled back to the savepoint.

​正确答案:B) One row is inserted into band 和 C) Two transactions commit​

(最终 band 表中有 1 行数据,且有两个事务被提交)


​技术解析​

Mermaid Chart  Create complex, visual diagrams with text. A smarter way of creating diagrams.20250627030517.png

​核心机制拆解​

  1. ​事务回滚机制​:

    • $connect->rollBack() 回滚 ​整个事务​(非仅保存点)
    • 撤销 beginTransaction() 后的所有操作 → ​第一次 INSERT 被丢弃​
  2. ​自动提交模式生效​:

    • 回滚后事务结束 → 后续操作在自动提交模式下执行
    • DELETE 和 INSERT 各自作为 ​独立事务立即提交​
  3. ​最终数据状态验证​:

操作 影响行数 持久化
第一次 INSERT +1 ❌ 回滚撤销
DELETE -N ✅ 永久生效
第二次 INSERT +1 ✅ 永久生效
→ ​净结果:1 行数据​(DELETE 清空后新插入)

​错误选项排除​

❌ ​A) 无事务提交​

  • 自动提交模式下 DELETE 和 INSERT ​各提交一个事务​ → 共 2 次提交

❌ ​D) 无数据插入​

  • 第二个 INSERT 成功执行 → 持久化 1 行数据

❌ ​E) 回滚到保存点​

  • rollBack() 回滚到事务开始(非 SAVEPOINT addsong)

  • 回滚到保存点需显式调用:

    $connect->exec("ROLLBACK TO addsong");  // 正确做法  
    

💡 ​开发警戒​:
PHP PDO 的 rollBack() ​总是回滚整个事务​!保存点需显式 SQL 回滚,且业务中慎用自动提交模式切换。
3b307690d7499afb7ae75b0af04dcc9.jpg

「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

文章被以下合辑收录

评论