多线程事务和锁定

Transaction and Locking with multiple threads

您好以下是问题场景:

我正在使用 MYSQL(Innodb 引擎),我的应用程序之一(C++/MYSQLCAPI)正在执行以下操作:

开始交易

截断 my_table

将数据文件加载到 table my_table.

如果以上命令[截断和加载]都成功,则提交

否则回滚

现在另一个应用程序 (C++/MYSQLCAPI) 正在通过以下命令每秒读取此 table。

select * 来自 my_table

错误:在这次读取尝试中,有时它得到 0 个数据,这可能是什么原因?

你看到一个空的 table 因为 truncate table has an implicit commit. If you need to change the entire table in a transaction you can use delete then insert, or try the rename solution presented in this answer

CREATE TABLE new LIKE real;
load `new` by whatever means
if something went wrong, don't do the next two steps.
RENAME TABLE real TO old, new TO real;
DROP TABLE old;

这避免了您提到的问题以及许多其他问题。特别是,它不需要特殊的事务处理; RENAME 是原子的并且非常快。