简体   繁体   English

使用InnoDB引擎在mysql中插入单行时是否需要事务处理?

[英]Is transaction needed when insert single line in mysql with InnoDB engine?

I used to use 我曾经用

<?php
$sql = "insert into test (owner) values ('owen')";
$db->autocommit(false);
if (!$db->query($sql))
    $db->rollback();
else
    $db->commit();
$db->close();
?>

However, today I run two insert php files in a same tables, without any action. 但是,今天我在同一张表中运行了两个insert php文件,没有任何操作。 It is simple like: 很简单,例如:

<?php
$sql = "insert into test (owner) values ('owen')"; //the other php is the same but replacing 'owen' to 'huhu'
for ($i = 0; $i < 100 * 1000; $i++) {
    $db->query($sql);
}
$db->close();
?>

I run two php files in two different consoles. 我在两个不同的控制台中运行两个php文件。 Then I got 200,000 records without any error. 然后我得到了200,000条记录,没有任何错误。 Does that mean using transaction manually is really not needed. 这是否意味着确实不需要手动使用事务。 As there are no conflicts. 由于没有冲突。

You do not need transactions for this. 您不需要为此进行交易。

Transactions exist to be able to roll back half-finished changes to the database. 存在事务以能够回滚对数据库完成的更改。 These only occur when you have a set of multiple statements changing the database which might be interrupted inbetween. 仅当您有一组更改数据库的语句可能在它们之间被中断时,才会发生这些情况。 Then often only some of the statements have been execute which might leave the database in a state which is not 'clean' from the applications point of view. 然后,通常仅执行了一些语句,这可能会使数据库处于从应用程序角度来看并非“干净”的状态。

A simple and good example is a money transfer between two tables: 一个简单而良好的示例是两个表之间的汇款:

  • first a removal from one table 首先从一张桌子上移走

  • then it is added to a second table 然后将其添加到第二个表

If this process is interrupted inbetween the money has vanished. 如果此过程在两者之间被中断,那么钱就消失了。 That is not intended, you probably want to be able to rollback. 那不是故意的,您可能希望能够回滚。

In your case however all statements are 'atomic', meaning they succeed or fail, but the databases state is always 'clean'. 但是,在您的情况下,所有语句都是“原子的”,这意味着它们成功或失败,但是数据库状态始终为“干净”。 It does not matter in this if it is a single or multiple clients running the statements. 不管是运行该语句的单个还是多个客户端,这都没有关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM