事务中的 LAST_INSERT_ID() 可靠吗?

发布于 2024-12-04 19:03:05 字数 484 浏览 0 评论 0原文

我正在使用 mysql/ado.net/C# 这是我的问题 我知道 mysql 是并发的,但是我有文件数据(缩略图名称)和数据库数据(行)要同步。

如果我开始一笔交易,但因任何原因失败,这会是一个问题吗?如果我在两个核心上同时运行这段代码,它们会互相破坏吗?我本质上需要知道 1)last_insert_id 是否依赖于不改变。 2) 如果一个事务使用所述 rowid,则另一事务不会使用它。

start transaction
insert statement, however i dont want it to be active yet;
select LAST_INSERT_ID()
File.Delete(lastid)//may exist from a transaction that failed
File.Move(thumbImage, lastid)
transaction.commit()//ok done

这安全吗?为什么或为什么不呢?

I am using mysql/ado.net/C# heres my problem
I know mysql is concurrent, however i have file data (the thumbname name) and db data (the row) to be in sync.

If i start a transaction and it fails for any reason will this be a problem? If i have this code ran at the same time on two cores will they clobber eachother? I essentially need to know if 1) the last_insert_id is dependable on not changing. 2) if one transaction uses said rowid that another transaction wont use it.

start transaction
insert statement, however i dont want it to be active yet;
select LAST_INSERT_ID()
File.Delete(lastid)//may exist from a transaction that failed
File.Move(thumbImage, lastid)
transaction.commit()//ok done

Is this safe? Why or why not?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

假扮的天使 2024-12-11 19:03:05

MySQL 的last_insert_id() 是可靠的,因为它始终是该特定连接执行的最后一个插入。它不会报告由其他连接创建的插入 ID,也不会报告您在两个连接之前执行的插入。实际插入发生在哪个 cpu 核心上以及在哪个核心上处理 last_insert_id() 调用并不重要。它始终是该连接的正确 ID 号。

如果回滚执行插入的事务,last_insert_id() 仍然会报告新的 id,即使它不再存在。但是,在后续插入中,该 id 不会被重用

MySQL's last_insert_id() is dependable in that it's always the LAST insert performed by THAT PARTICULAR connection. It won't report an insert id created by some other connection, it won't report an insert that you did two connections ago. It won't matter which cpu core the actual insert occured on, and which core the last_insert_id() call is processed on. It will always be the right ID number for that connection.

If you roll back a transaction that did an insert, last_insert_id() will STILL report that new id, even though it no longer exists. The id will not be reused, however, in a subsequent insert

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文