gpt4 book ai didi

mysql - 如何在单个事务中持久化具有主从关系的表?

转载 作者:行者123 更新时间:2023-11-29 02:27:45 25 4
gpt4 key购买 nike

我正在尝试使用 Delphi XE3 和 Zeos 7.0.4 在 MySQL 5.6 中保留两个具有主从关系的表。当我在 master 上执行 ApplyUpdates 时,自动递增字段的值保持为 0。我需要自动增量值,因此我可以将明细表与来自 ApplyUpdates 的主表的 ID 字段链接起来。我使用 ZConnection with AutoCommit = FALSE and TransactionIsolationLevel = tiReadCommitted, ZQuery with CachedUpdates = TRUE。我错过了什么?

ZQPerson.Append;
ZQEmployee.Append;
try
ZQPersonName.Value := Edit1.Text;
ZQPerson.ApplyUpdates; //Here I expected to have the auto increment value on the Id field of ZQPerson, but it returns always 0
ZQEmployeePersonID.Value := ZQPersonId.Value; //Here I'd link Employee to it's Person record
ZQEmployeeRegNo.Value := StrToInt(Edit2.Text);
ZQEmployee.ApplyUpdates;
ZConnection1.Commit; //Here I would persist both tables in a single transaction to avoid master table without details
except
ZQPerson.CancelUpdates;
ZQEmployee.CancelUpdates;
ZConnection1.Rollback; //In case of exceptions rollback everything
raise;
end;
ZQPerson.CommitUpdates;
ZQEmployee.CommitUpdates;

我的 ZSQLMonitor 跟踪是这样的:

2013-08-29 00:01:23 cat: Execute, proto: mysql-5, msg: INSERT INTO person (Id, name) VALUES (NULL, 'Edit1') --> This is just after ZQPerson.ApplyUpdates
2013-08-29 00:01:50 cat: Execute, proto: mysql-5, msg: INSERT INTO employee (Id, RegNo, ProductId) VALUES (NULL, 1000, 0), errcode: 1452, error: Cannot add or update a child row: a foreign key constraint fails (`test`.`employee`, CONSTRAINT `FK_A6085E0491BDF8EE` FOREIGN KEY (`PersonId`) REFERENCES `person` (`Id`) --> This is just after ZQEmployee.ApplyUpdates
2013-08-29 00:02:05 cat: Execute, proto: mysql-5, msg: Native Rollback call --> Rollback after Exception on the ZQEmployee.ApplyUpdates

最佳答案

您是否正在使用 ZConnection1.StartTransaction 开始事务?我也认为你必须在调用 ZQuery1.ApplyUpdates 后刷新 ZQuery1 以获得新的 id-

阅读您的评论,您一定是在执行不带 where 子句的 select * 吗?正确的?我可以推荐你使用这种方法:

1) 选择并增加当前的自动增量值
2) select from master table where id=[step1 id]//当然是空的
3) 使用步骤 1 中的 id 添加详细信息
4) 分配主数据集中的id
5) 应用两个更新

关于mysql - 如何在单个事务中持久化具有主从关系的表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18495309/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com