简体   繁体   中英

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. 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. Then I got 200,000 records without any error. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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