search
HomeDatabaseMysql TutorialWhat is transaction processing in mysql

What is transaction processing in mysql

Nov 11, 2022 pm 05:32 PM
mysqltransaction processing

In mysql, transaction processing is a mechanism used to manage MySQL operations that must be performed in batches to ensure that the database does not contain incomplete operation results; transaction processing can be used to maintain the integrity of the database. It is guaranteed that batches of MySQL operations will not be stopped midway, they will either be fully executed or not executed at all.

What is transaction processing in mysql

The operating environment of this tutorial: windows7 system, mysql8 version, Dell G3 computer.

Transaction processing

Transaction processing can be used to maintain the integrity of the database. It guarantees that batches of MySQL operations are either fully executed or not executed at all.

For example, in the personnel management system, deleting a person requires deleting not only the basic information of the person, but also the information related to the person, such as mailboxes, articles, etc. In this way, these databases The operation statement constitutes a transaction!

Transaction processing is a mechanism used to manage MySQL operations that must be performed in batches to ensure that the database does not contain incomplete operation results. Using transaction processing, you can ensure that a set of operations will not stop midway, they will either be executed as a whole, or not executed at all (unless explicitly instructed) . If no errors occur, the entire set of statements is committed (written) to the database table. If an error occurs, roll back (undo) to restore the database to a known and safe state.

Generally speaking, a transaction must meet four conditions (ACID): Atomicity(Atomicity, or indivisibility), Consistency(Consistency), isolation( Isolation, also known as independence), persistence(Durability).

  • Atomicity: All operations in a transaction will either be completed or not completed, and will not end in any intermediate link. If an error occurs during the execution of the transaction, it will be rolled back to the state before the transaction started, as if the transaction had never been executed.

  • Consistency: The integrity of the database is not destroyed before the transaction starts and after the transaction ends. This means that the data written must fully comply with all preset rules, including the accuracy and concatenation of the data, and that the subsequent database can spontaneously complete the predetermined work.

  • Isolation: The database allows multiple concurrent transactions to read, write and modify its data at the same time. Isolation can prevent multiple transactions from being executed concurrently due to Cross execution leads to data inconsistency. Transaction isolation is divided into different levels, including read uncommitted, read committed, repeatable read and serializable.

  • Persistence: After the transaction is completed, the modification to the data is permanent and will not be lost even if the system fails.

1.1 Keywords

When using transactions and transaction processing, there are several key words that appear repeatedly. Here are a few terms you need to know about transaction processing:

  • Transaction: refers to a set of SQL statements;
  • Rollback ( rollback): refers to the process of undoing the specified SQL statement ;
  • Submit (commit): refers to writing the unstored SQL statement results to the database table;
  • Savepoint: refers to the temporary placeholder (placeholder) set in the transaction, for which you can issue a rollback (different from rolling back the entire transaction) .

1.2 Transaction Control Statement

The key to managing transaction processing is to decompose SQL statement groups into logical blocks, and clearly specify when the data should be rolled back and when it should not be rolled back.

##1.2.1 START TRANSACTION Start transaction

MySQL uses the following statement to identify the start of a

transaction:

START  TRANSACTION

1.2.2 COMMIT

General MySQL statements are executed and written directly against database tables. This is the so-called implicit commit (implicit commit), that is, the submission (write or save) operation is performed automatically.
         However, In the transaction block, the commit will not be performed implicitly. To make an explicit commit, use the COMMIT statement. COMMIT commits the transaction and makes all modifications that have been made to the database permanent; As shown below:

START TRANSACTION  
DELETE FROM orderitems WHERE order_num = 20010;
DELETE FROM orders WHERE order_num = 20010;
COMMIT;

In this example, order 20010 is completely deleted from the system. Because it involves updating two database tables, orders and orderItems, a transaction block is used to ensure that the order is not partially deleted. The final COMMIT statement only writes out changes if no errors occur. If the first DELETE works but the second fails, the DELETE is not committed (in fact, it is automatically revoked).

1.2.3 ROLLBACK

MySQL’s ROLLBACK command is used to roll back (undo) the MySQL statement , As follows:

SELECT * FROM orderitems;
START TRANSACTION        -- 事务开始
DELETE FROM orderitems;
SELECT * FROM orderitems;
ROLLBACK;
SELECT * FROM orderitems;

The above example starts by displaying the contents of the ordertotals table. First execute a SELECT to show that the table is not empty. Then start a
transaction processing , use a DELETE statement to delete all rows in ordertotals. Another SELECT statement verifies that ordertotals is indeed empty. At this time, use a ROLLBACK statement to roll back all statements after START TRANSACTION , and the last SELECT statement shows that the table is not empty.
      Obviously, ROLLBACK can only be used within a transaction (after executing a START TRANSACTION command) .

Transaction processing is used to manage INSERT, UPDATE and DELETE statements. You cannot roll back a SELECT statement. (This also makes little sense.) You cannot roll back a CREATE or DROP operation. These two statements can be used within a transaction block, but they will not be undone if you perform a rollback.

1.2.4 Retention point

          Simple ROLLBACK and COMMIT statements can write or cancel the entire transaction . However, this is only possible for simple transactions; more complex transactions may require partial commit or rollback.

In order to support rolling back part of the transaction, placeholders must be placed at appropriate locations in the transaction block. This way, if you need to roll back, you can fall back to a placeholder. These placeholders are called retention points. In order to create a placeholder, you can use the following SAVEPOINT statement:

SAVEPOINT delete1;

Each retain point has a unique name that identifies it, so that when rolling back, MySQL Know where to fall back to. The following operations can fall back to the given retention point:

ROLLBACK TO delete1;

1.2.5 Change the default submission behavior

As mentioned, the default The MySQL behavior is to automatically commit all changes. In other words, any time you execute a MySQL statement, the statement is actually executed against the table, and the changes take effect immediately. To instruct MySQL not to automatically commit changes, you need to use the following statement:

SET autocommit = 0;

      autocommit flag determines whether to automatically commit changes , regardless of whether there is a COMMIT statement. Setting autocommit to 0 (false) instructs MySQL not to automatically commit changes (until autocommit is set to true).

Flag for connection Specialized autocommit flag is for each connection rather than the server.

1.3 Transaction processing methods

There are two main methods for transaction processing in MYSQL:

Use BEGIN, ROLLBACK, COMMIT to implement
  • 1)
BEGIN

Start a transaction 2)

ROLLBACK

Transaction Rollback 3)

COMMIT

Transaction confirmation Example:

START TRANSACTION; -- 开始事务
INSERT INTO runoob_transaction_test VALUE(5);
INSERT INTO runoob_transaction_test VALUE(6);
COMMIT; -- 提交事务

select * from runoob_transaction_test;

  • Use SET directly to change MySQL's automatic submission mode:

SET AUTOCOMMIT=0 Disable automatic submission

        SET AUTOCOMMIT=1 Turn on automatic submission

[Related recommendations: mysql video tutorial]

The above is the detailed content of What is transaction processing in mysql. For more information, please follow other related articles on the PHP Chinese website!

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
Explain the role of InnoDB redo logs and undo logs.Explain the role of InnoDB redo logs and undo logs.Apr 15, 2025 am 12:16 AM

InnoDB uses redologs and undologs to ensure data consistency and reliability. 1.redologs record data page modification to ensure crash recovery and transaction persistence. 2.undologs records the original data value and supports transaction rollback and MVCC.

What are the key metrics to look for in an EXPLAIN output (type, key, rows, Extra)?What are the key metrics to look for in an EXPLAIN output (type, key, rows, Extra)?Apr 15, 2025 am 12:15 AM

Key metrics for EXPLAIN commands include type, key, rows, and Extra. 1) The type reflects the access type of the query. The higher the value, the higher the efficiency, such as const is better than ALL. 2) The key displays the index used, and NULL indicates no index. 3) rows estimates the number of scanned rows, affecting query performance. 4) Extra provides additional information, such as Usingfilesort prompts that it needs to be optimized.

What is the Using temporary status in EXPLAIN and how to avoid it?What is the Using temporary status in EXPLAIN and how to avoid it?Apr 15, 2025 am 12:14 AM

Usingtemporary indicates that the need to create temporary tables in MySQL queries, which are commonly found in ORDERBY using DISTINCT, GROUPBY, or non-indexed columns. You can avoid the occurrence of indexes and rewrite queries and improve query performance. Specifically, when Usingtemporary appears in EXPLAIN output, it means that MySQL needs to create temporary tables to handle queries. This usually occurs when: 1) deduplication or grouping when using DISTINCT or GROUPBY; 2) sort when ORDERBY contains non-index columns; 3) use complex subquery or join operations. Optimization methods include: 1) ORDERBY and GROUPB

Describe the different SQL transaction isolation levels (Read Uncommitted, Read Committed, Repeatable Read, Serializable) and their implications in MySQL/InnoDB.Describe the different SQL transaction isolation levels (Read Uncommitted, Read Committed, Repeatable Read, Serializable) and their implications in MySQL/InnoDB.Apr 15, 2025 am 12:11 AM

MySQL/InnoDB supports four transaction isolation levels: ReadUncommitted, ReadCommitted, RepeatableRead and Serializable. 1.ReadUncommitted allows reading of uncommitted data, which may cause dirty reading. 2. ReadCommitted avoids dirty reading, but non-repeatable reading may occur. 3.RepeatableRead is the default level, avoiding dirty reading and non-repeatable reading, but phantom reading may occur. 4. Serializable avoids all concurrency problems but reduces concurrency. Choosing the appropriate isolation level requires balancing data consistency and performance requirements.

MySQL vs. Other Databases: Comparing the OptionsMySQL vs. Other Databases: Comparing the OptionsApr 15, 2025 am 12:08 AM

MySQL is suitable for web applications and content management systems and is popular for its open source, high performance and ease of use. 1) Compared with PostgreSQL, MySQL performs better in simple queries and high concurrent read operations. 2) Compared with Oracle, MySQL is more popular among small and medium-sized enterprises because of its open source and low cost. 3) Compared with Microsoft SQL Server, MySQL is more suitable for cross-platform applications. 4) Unlike MongoDB, MySQL is more suitable for structured data and transaction processing.

How does MySQL index cardinality affect query performance?How does MySQL index cardinality affect query performance?Apr 14, 2025 am 12:18 AM

MySQL index cardinality has a significant impact on query performance: 1. High cardinality index can more effectively narrow the data range and improve query efficiency; 2. Low cardinality index may lead to full table scanning and reduce query performance; 3. In joint index, high cardinality sequences should be placed in front to optimize query.

MySQL: Resources and Tutorials for New UsersMySQL: Resources and Tutorials for New UsersApr 14, 2025 am 12:16 AM

The MySQL learning path includes basic knowledge, core concepts, usage examples, and optimization techniques. 1) Understand basic concepts such as tables, rows, columns, and SQL queries. 2) Learn the definition, working principles and advantages of MySQL. 3) Master basic CRUD operations and advanced usage, such as indexes and stored procedures. 4) Familiar with common error debugging and performance optimization suggestions, such as rational use of indexes and optimization queries. Through these steps, you will have a full grasp of the use and optimization of MySQL.

Real-World MySQL: Examples and Use CasesReal-World MySQL: Examples and Use CasesApr 14, 2025 am 12:15 AM

MySQL's real-world applications include basic database design and complex query optimization. 1) Basic usage: used to store and manage user data, such as inserting, querying, updating and deleting user information. 2) Advanced usage: Handle complex business logic, such as order and inventory management of e-commerce platforms. 3) Performance optimization: Improve performance by rationally using indexes, partition tables and query caches.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.