search
HomeDatabaseMysql Tutorial深入理解MySQL中的事务机制_MySQL

 使用数据库事务可以确保除事务性单元内的所有操作都成功完成。MySQL中的InnoDB引擎的表才支持transaction。在一个事务里,如果出现一个数据库操作失败了,事务内的所有操作将被回滚,数据库将会回到事务前的初始状态。有一些不能被回滚的语句:将在本文的最后讨论。

在一个web应用中,会很经常遇到需要使用事务的地方,要么希望若干语句都执行成功,要么都不执行,如果出现有些执行成功,而其他的失败将会导致数据损坏。

在这篇文章的例子中,我们使用下面的两张表"employee"和"telephone",下面是SQL语句(作为参考):

创建 employee表:
 

CREATE TABLE `employee` (
 `id` int NOT NULL AUTO_INCREMENT,
 `first_name` varchar(100) NOT NULL,
 `last_name` varchar(100) NOT NULL,
 `job_title` varchar(100) DEFAULT NULL,
 `salary` double DEFAULT NULL,
 `notes` text,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

向employee中插入数据
 

INSERT INTO `employee` (`first_name`, `last_name`, `job_title`, `salary`) VALUES
            ('Robin', 'Jackman', 'Software Engineer', 5500),
            ('Taylor', 'Edward', 'Software Architect', 7200),
            ('Vivian', 'Dickens', 'Database Administrator', 6000),
            ('Harry', 'Clifford', 'Database Administrator', 6800),
            ('Eliza', 'Clifford', 'Software Engineer', 4750),
            ('Nancy', 'Newman', 'Software Engineer', 5100),
            ('Melinda', 'Clifford', 'Project Manager', 8500),
            ('Harley', 'Gilbert', 'Software Architect', 8000);

创建telephone表
 

CREATE TABLE `telephone` (
 `id` int NOT NULL AUTO_INCREMENT,
 `employee_id` int DEFAULT NULL,
 `type` varchar(20) NOT NULL,
 `no` varchar(50) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

向telephone表插入数据
 

INSERT INTO `telephone` (`employee_id`, `type`, `no`) VALUES
            (1, 'mobile',  '245-249697'),
            (2, 'mobile',  '270-235969'),
            (2, 'land',   '325-888885'),
            (3, 'mobile',  '270-684972'),
            (4, 'mobile',  '245-782365'),           
            (4, 'land',   '325-888886'),
            (5, 'mobile',  '245-537891'),
            (6, 'mobile',  '270-359457'),
            (7, 'mobile',  '245-436589'),                           
            (7, 'land',   '325-888887'),
            (8, 'mobile',  '245-279164'),                           
            (8, 'land',   '325-888888');

2015626102143340.jpg (447×584)

    设想你需要一个新的叫做Grace Williams雇员,并带有他的电话号码信息。你可能会执行下面两句sql: 
 

INSERT INTO `employee` (`id`, `first_name`, `last_name`,
`job_title`, `salary`) VALUES (9, 'Grace', 'Williams',
'Softwaree Engineer', 5000);
 
INSERT INTO `telephone` (`id`, `employee_id`, `type`,
`no`) VALUES (13, 9, 'mobile', '270-598712');

让我们看看第二个语句,在第一个语句中,employee_id是在第一条语句中指定的,设想一下,当第一条语句失败,而第二条语句成功的状况。在这种状况下,telephone表中就会有一条employee_id为9的记录,而employee表中并没有id为9的记录,而如果将这两个语句放在MySQL事务中,如果第一条语句失败,那么第二条语句也将回滚,从而不会造成这种问题。

在PHP(PHP参考文档)中我们可以使用如下的方式启用事务:
 

<&#63;php
 
//$salary = 5000;
$salary = '$5000';
 
/* Change database details according to your database */
$dbConnection = mysqli_connect('localhost', 'robin', 'robin123', 'company_db');
 
mysqli_autocommit($dbConnection, false);
 
$flag = true;
 
$query1 = "INSERT INTO `employee` (`id`, `first_name`, `last_name`, `job_title`, `salary`) VALUES (9, 'Grace', 'Williams', 'Softwaree Engineer', $salary)";
$query2 = "INSERT INTO `telephone` (`id`, `employee_id`, `type`, `no`) VALUES (13, 9, 'mobile', '270-598712')";
 
$result = mysqli_query($dbConnection, $query1);
 
if (!$result) {
  $flag = false;
  echo "Error details: " . mysqli_error($dbConnection) . ". ";
}
 
$result = mysqli_query($dbConnection, $query2);
 
if (!$result) {
  $flag = false;
  echo "Error details: " . mysqli_error($dbConnection) . ". ";
}
 
if ($flag) {
 
  mysqli_commit($dbConnection);
  echo "All queries were executed successfully";
 
} else {
 
  mysqli_rollback($dbConnection);
  echo "All queries were rolled back"; 
 
}
 
mysqli_close($dbConnection);
 
&#63;>


    当你执行mysqli_query函数的时候,结果被立即提交到了数据库。使用mysqli_autocommit函数,可以关闭自动提交,执行结果只有当你想提交的时候才提交。
    如果任何语句执行失败我们都可以设置$flag变量为false。如果有很多语句要执行,可以考虑将他们放在for循环中。
    最后,如果flag是true(也就是没有错误发生),我们使用mysqli_commit提交事务。否则我们使用mysqli_rollback回滚事务。

所以,事务可以在某种程度上帮助我们维护数据的完整和正确,另外,为了保证数据无误,我们还推荐使用外键。

并不是所有的语句都是支持事务的,例如,如果使用CREATE TABLE或者ALTER TABLE语句,需要了解更多可以参考MySQL手册查看哪些语句不能回滚。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does MySQL's licensing compare to other database systems?How does MySQL's licensing compare to other database systems?Apr 25, 2025 am 12:26 AM

MySQL uses a GPL license. 1) The GPL license allows the free use, modification and distribution of MySQL, but the modified distribution must comply with GPL. 2) Commercial licenses can avoid public modifications and are suitable for commercial applications that require confidentiality.

When would you choose InnoDB over MyISAM, and vice versa?When would you choose InnoDB over MyISAM, and vice versa?Apr 25, 2025 am 12:22 AM

The situations when choosing InnoDB instead of MyISAM include: 1) transaction support, 2) high concurrency environment, 3) high data consistency; conversely, the situation when choosing MyISAM includes: 1) mainly read operations, 2) no transaction support is required. InnoDB is suitable for applications that require high data consistency and transaction processing, such as e-commerce platforms, while MyISAM is suitable for read-intensive and transaction-free applications such as blog systems.

Explain the purpose of foreign keys in MySQL.Explain the purpose of foreign keys in MySQL.Apr 25, 2025 am 12:17 AM

In MySQL, the function of foreign keys is to establish the relationship between tables and ensure the consistency and integrity of the data. Foreign keys maintain the effectiveness of data through reference integrity checks and cascading operations. Pay attention to performance optimization and avoid common errors when using them.

What are the different types of indexes in MySQL?What are the different types of indexes in MySQL?Apr 25, 2025 am 12:12 AM

There are four main index types in MySQL: B-Tree index, hash index, full-text index and spatial index. 1.B-Tree index is suitable for range query, sorting and grouping, and is suitable for creation on the name column of the employees table. 2. Hash index is suitable for equivalent queries and is suitable for creation on the id column of the hash_table table of the MEMORY storage engine. 3. Full text index is used for text search, suitable for creation on the content column of the articles table. 4. Spatial index is used for geospatial query, suitable for creation on geom columns of locations table.

How do you create an index in MySQL?How do you create an index in MySQL?Apr 25, 2025 am 12:06 AM

TocreateanindexinMySQL,usetheCREATEINDEXstatement.1)Forasinglecolumn,use"CREATEINDEXidx_lastnameONemployees(lastname);"2)Foracompositeindex,use"CREATEINDEXidx_nameONemployees(lastname,firstname);"3)Forauniqueindex,use"CREATEU

How does MySQL differ from SQLite?How does MySQL differ from SQLite?Apr 24, 2025 am 12:12 AM

The main difference between MySQL and SQLite is the design concept and usage scenarios: 1. MySQL is suitable for large applications and enterprise-level solutions, supporting high performance and high concurrency; 2. SQLite is suitable for mobile applications and desktop software, lightweight and easy to embed.

What are indexes in MySQL, and how do they improve performance?What are indexes in MySQL, and how do they improve performance?Apr 24, 2025 am 12:09 AM

Indexes in MySQL are an ordered structure of one or more columns in a database table, used to speed up data retrieval. 1) Indexes improve query speed by reducing the amount of scanned data. 2) B-Tree index uses a balanced tree structure, which is suitable for range query and sorting. 3) Use CREATEINDEX statements to create indexes, such as CREATEINDEXidx_customer_idONorders(customer_id). 4) Composite indexes can optimize multi-column queries, such as CREATEINDEXidx_customer_orderONorders(customer_id,order_date). 5) Use EXPLAIN to analyze query plans and avoid

Explain how to use transactions in MySQL to ensure data consistency.Explain how to use transactions in MySQL to ensure data consistency.Apr 24, 2025 am 12:09 AM

Using transactions in MySQL ensures data consistency. 1) Start the transaction through STARTTRANSACTION, and then execute SQL operations and submit it with COMMIT or ROLLBACK. 2) Use SAVEPOINT to set a save point to allow partial rollback. 3) Performance optimization suggestions include shortening transaction time, avoiding large-scale queries and using isolation levels reasonably.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor