Table of Contents
1. MySQL transaction
1. The concept of transaction
2. ACID characteristics of transactions
3. The mutual influence between things
2. Mysql and transaction isolation level
1. Query global transaction isolation level
2. Query Session transaction isolation level
3. Set global transaction isolation level
4. Set session transaction isolation level
三、事务控制语句
1、相关语句
2、案例
3、使用 set 设置控制事务
四、MySQL 存储引擎
1、存储引擎概念介绍
2、查看系统支持的存储引擎
3、查看表使用的存储引擎
4、修改存储引擎
Home Database Mysql Tutorial Mysql transaction and storage engine instance analysis

Mysql transaction and storage engine instance analysis

May 27, 2023 pm 08:29 PM
mysql

1. MySQL transaction

1. The concept of transaction

(1) A transaction is a mechanism, an operation sequence, which includes a set of database operation commands and combines all commands Submit or revoke operation requests to the system as a whole, that is, this set of database commands will either be executed or none of them will be executed.

(2) A transaction is an indivisible logical unit of work. When performing concurrent operations on a database system, a transaction is the smallest control unit.

(3) Scenarios of database systems operated by multiple users at the same time, such as banks, insurance companies, securities trading systems, etc., suitable for transaction processing. (4) Transactions ensure data consistency through transaction integrity.

2. ACID characteristics of transactions

Note: ACID refers to the four characteristics that transactions should have in a reliable database management system (DBMS): Atomicity , Consistency, Isolation, Durability. These are several characteristics that a reliable database should have.

(1) Transactions are atomic, that is to say, the operations in the transaction are either all executed or not executed at all and are indivisible. a. A transaction is a complete operation, and the elements of the transaction are inseparable.

b. All elements in the transaction must be committed or rolled back as a whole.

c. If any element in the transaction fails, the entire transaction will fail.

(2) Consistency: means that the integrity constraints of the database are not destroyed before the transaction starts and after the transaction ends.

a. When the transaction is completed, the data must be in a consistent state.

b. Before the transaction starts, the data stored in the database is in a consistent state.

c. In ongoing transactions, data may be in an inconsistent state.

d. When the transaction completes successfully, the data must return to a known consistent state again.

(3) Isolation: When multiple transactions operate the same data at the same time, in a concurrent environment, each transaction can use its own independent complete data area. All concurrent transactions that modify data are isolated from each other, indicating that a transaction must be independent and that it should not depend on or affect other transactions in any way. A transaction that modifies data can access the data before another transaction that uses the same data begins, or after another transaction that uses the same data ends.

(4) Persistence: After the transaction is completed, the changes made to the database by the transaction are permanently stored in the database and will not be rolled back.

a, means that regardless of whether the system fails, the results of transaction processing are permanent.

b. Once a transaction is committed, the effects of the transaction will be permanently retained in the database.

Summary: In transaction management, atomicity is the foundation, isolation is the means, consistency is the purpose, and durability is the result.

3. The mutual influence between things

(1) Dirty reading: One transaction reads uncommitted data of another transaction, and this data may be rolled back.

When two identical queries are executed continuously in a transaction, but different results are obtained, this situation is called non-repeatable read. This is caused by the commit of modifications by other transactions in the system at query time.

Restatement: Phantom reading refers to when a transaction modifies certain data rows in a table, but another transaction inserts several new rows of data at the same time, causing the first transaction to find several more rows when querying. row data. At the same time, another transaction modified the table and inserted a new row of data. Users who operated on the previous transaction will be surprised to find that there are still unmodified data rows in the table, as if they were hallucinating.

(4). Lost update: Two transactions read the same record at the same time. A modifies the record first, and B also modifies the record (B does not know that A has modified it). After B submits the data, B's modification results are overwritten. The modification result of A.

2. Mysql and transaction isolation level

(1), read uncommitted: read uncommitted data, do not solve dirty reads

(2), read committed: Reading submitted data can solve dirty reads

(3), repeatable read: Rereading can solve dirty reads and non-repeatable reads------------- Mysql defaults to

(4), serializable: serialization, which can solve dirty reads, non-repeatable reads and virtual reads---------------- equivalent to a lock table Note: The default transaction processing level of mysql is repeatable read, while Oracle and SQL Server are read committed

1. Query global transaction isolation level

show global variables like '%isolation%';
或
select @@global.tx_isolation;

Mysql transaction and storage engine instance analysis

2. Query Session transaction isolation level

show session variables like '%isolation%';
SELECT @@session.tx_isolation; 
SELECT @@tx_isolation;

Mysql transaction and storage engine instance analysis

3. Set global transaction isolation level

set global transaction isolation level read committed;
show global variables like '%isolation%';

Mysql transaction and storage engine instance analysis

4. Set session transaction isolation level

set session transaction isolation level read committed;
show session variables like '%isolation%';

Mysql transaction and storage engine instance analysis

三、事务控制语句

1、相关语句

begin; 开启事务
commit; 提交事务,使已对数据库进行的所有修改变为永久性的
rollback; 回滚事务,撤销正在进行的所有未提交的修改
savepoint s1; 建立回滚点,s1为回滚点名称,一个事务中可以有多个
rollback to s1; 回滚到s1回滚点

2、案例

①、创建表

create database school;
use school;
create table Fmoney(
id int(10) primary key not null,  
name varchar(20),  
money decimal(5,2));

insert into Fmoney values ('1','srs1','100');
insert into Fmoney values ('2','srs2','200');
select * from Fmoney;

Mysql transaction and storage engine instance analysis

②、测试提交事务

begin;
update Fmoney set money= money - 100 where name='srs2';
commit;
quit

mysql -u root -p
use school;
select * from Fmoney;

Mysql transaction and storage engine instance analysis

③、测试回滚事务

begin;
update Fmoney set money= money + 100 where name='srs2';
select * from Fmoney;
rollback;

select * from Fmoney;

Mysql transaction and storage engine instance analysis

④、测试多点回滚

begin;
update Fmoney set money= money + 100 where name='srs2';
select * from Fmoney;
savepoint a;
update Fmoney set money= money + 100 where name='srs1';
select * from Fmoney;
savepoint b;
insert into Fmoney values ('3','srs3','300');
select * from Fmoney;

rollback to b;
select * from Fmoney;

Mysql transaction and storage engine instance analysis

Mysql transaction and storage engine instance analysis

3、使用 set 设置控制事务

SET AUTOCOMMIT=0;                        #禁止自动提交
SET AUTOCOMMIT=1;                        #开启自动提交,Mysql默认为1
SHOW VARIABLES LIKE 'AUTOCOMMIT';        #查看Mysql中的AUTOCOMMIT值

如果没有开启自动提交,当前会话连接的mysql的所有操作都会当成一个事务直到你输入rollback|commit;当前事务才算结束。当前事务结束前新的mysql连接时无法读取到任何当前会话的操作结果。
如果开起了自动提交,mysql会把每个sql语句当成一个事务,然后自动的commit。
当然无论开启与否,begin; commit|rollback; 都是独立的事务。

Mysql transaction and storage engine instance analysis

四、MySQL 存储引擎

1、存储引擎概念介绍

(1)MySQL中的数据用各种不同的技术存储在文件中,每一种技术都使用不同的存储机制、索引技巧、锁定水平,并最终提供不同的功能和能力,这些不同的技术以及配套的功能在MySQL中称为存储引擎。

(2)存储引擎是MySQL将数据存储在文件系统中的存储方式或者存储格式

(3)MySQL 常用的存储引擎有: a、MylSAM b、InnoDB

(4)MySQL数据库中的组件,负责执行实际的数据I/O操作

(5)MySQL系统中,存储引擎处于文件系统之.上,在数据保存到数据文件之前会传输到存储引擎,之后按照各个存储引擎的存储格式进行存储。

2、查看系统支持的存储引擎

show engines;

Mysql transaction and storage engine instance analysis

3、查看表使用的存储引擎

(1)方法一:直接查看
show table status from 库名 where name='表名'\G;
例:
show table status from school where name='class'\G;

(2)方法二:进入数据库查看
use 库名;
show create table 表名\G;

例:
use school;
show create table class\G;

Mysql transaction and storage engine instance analysis

4、修改存储引擎

(1) 方法一:通过 alter table 修改
use 库名;
alter table 表名 engine=MyISAM;

例:
use school;
alter table class engine=MYISAM;

(2)方法二:通过修改 /etc/my.cnf 配置文件,指定默认存储引擎并重启服务
注意:此方法只对修改了配置文件并重启mysql服务后新创建的表有效,已经存在的表不会有变更。
vim /etc/my.cnf
......
[mysqld]
......
default-storage-engine=INNODB

systemctl restart mysql.service


(3)方法三:通过 create table 创建表时指定存储引擎
use 库名;
create table 表名(字段1 数据类型,...) engine=MyISAM;

例:
mysql -u root -p
use school;
create table test7(id int(10) not null,name varchar(20) not null) engine=MyISAM;

Mysql transaction and storage engine instance analysis

Mysql transaction and storage engine instance analysis

Mysql transaction and storage engine instance analysis

The above is the detailed content of Mysql transaction and storage engine instance analysis. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Handling character sets and collations issues in MySQL Handling character sets and collations issues in MySQL Jul 08, 2025 am 02:51 AM

Character set and sorting rules issues are common when cross-platform migration or multi-person development, resulting in garbled code or inconsistent query. There are three core solutions: First, check and unify the character set of database, table, and fields to utf8mb4, view through SHOWCREATEDATABASE/TABLE, and modify it with ALTER statement; second, specify the utf8mb4 character set when the client connects, and set it in connection parameters or execute SETNAMES; third, select the sorting rules reasonably, and recommend using utf8mb4_unicode_ci to ensure the accuracy of comparison and sorting, and specify or modify it through ALTER when building the library and table.

Implementing Transactions and Understanding ACID Properties in MySQL Implementing Transactions and Understanding ACID Properties in MySQL Jul 08, 2025 am 02:50 AM

MySQL supports transaction processing, and uses the InnoDB storage engine to ensure data consistency and integrity. 1. Transactions are a set of SQL operations, either all succeed or all fail to roll back; 2. ACID attributes include atomicity, consistency, isolation and persistence; 3. The statements that manually control transactions are STARTTRANSACTION, COMMIT and ROLLBACK; 4. The four isolation levels include read not committed, read submitted, repeatable read and serialization; 5. Use transactions correctly to avoid long-term operation, turn off automatic commits, and reasonably handle locks and exceptions. Through these mechanisms, MySQL can achieve high reliability and concurrent control.

Connecting to MySQL Database Using the Command Line Client Connecting to MySQL Database Using the Command Line Client Jul 07, 2025 am 01:50 AM

The most direct way to connect to MySQL database is to use the command line client. First enter the mysql-u username -p and enter the password correctly to enter the interactive interface; if you connect to the remote database, you need to add the -h parameter to specify the host address. Secondly, you can directly switch to a specific database or execute SQL files when logging in, such as mysql-u username-p database name or mysql-u username-p database name

Using Common Table Expressions (CTEs) in MySQL 8 Using Common Table Expressions (CTEs) in MySQL 8 Jul 12, 2025 am 02:23 AM

CTEs are a feature introduced by MySQL8.0 to improve the readability and maintenance of complex queries. 1. CTE is a temporary result set, which is only valid in the current query, has a clear structure, and supports duplicate references; 2. Compared with subqueries, CTE is more readable, reusable and supports recursion; 3. Recursive CTE can process hierarchical data, such as organizational structure, which needs to include initial query and recursion parts; 4. Use suggestions include avoiding abuse, naming specifications, paying attention to performance and debugging methods.

Designing a Robust MySQL Database Backup Strategy Designing a Robust MySQL Database Backup Strategy Jul 08, 2025 am 02:45 AM

To design a reliable MySQL backup solution, 1. First, clarify RTO and RPO indicators, and determine the backup frequency and method based on the acceptable downtime and data loss range of the business; 2. Adopt a hybrid backup strategy, combining logical backup (such as mysqldump), physical backup (such as PerconaXtraBackup) and binary log (binlog), to achieve rapid recovery and minimum data loss; 3. Test the recovery process regularly to ensure the effectiveness of the backup and be familiar with the recovery operations; 4. Pay attention to storage security, including off-site storage, encryption protection, version retention policy and backup task monitoring.

Strategies for MySQL Query Performance Optimization Strategies for MySQL Query Performance Optimization Jul 13, 2025 am 01:45 AM

MySQL query performance optimization needs to start from the core points, including rational use of indexes, optimization of SQL statements, table structure design and partitioning strategies, and utilization of cache and monitoring tools. 1. Use indexes reasonably: Create indexes on commonly used query fields, avoid full table scanning, pay attention to the combined index order, do not add indexes in low selective fields, and avoid redundant indexes. 2. Optimize SQL queries: Avoid SELECT*, do not use functions in WHERE, reduce subquery nesting, and optimize paging query methods. 3. Table structure design and partitioning: select paradigm or anti-paradigm according to read and write scenarios, select appropriate field types, clean data regularly, and consider horizontal tables to divide tables or partition by time. 4. Utilize cache and monitoring: Use Redis cache to reduce database pressure and enable slow query

Optimizing complex JOIN operations in MySQL Optimizing complex JOIN operations in MySQL Jul 09, 2025 am 01:26 AM

TooptimizecomplexJOINoperationsinMySQL,followfourkeysteps:1)EnsureproperindexingonbothsidesofJOINcolumns,especiallyusingcompositeindexesformulti-columnjoinsandavoidinglargeVARCHARindexes;2)ReducedataearlybyfilteringwithWHEREclausesandlimitingselected

Analyzing Query Execution with MySQL EXPLAIN Analyzing Query Execution with MySQL EXPLAIN Jul 12, 2025 am 02:07 AM

MySQL's EXPLAIN is a tool used to analyze query execution plans. You can view the execution process by adding EXPLAIN before the SELECT query. 1. The main fields include id, select_type, table, type, key, Extra, etc.; 2. Efficient query needs to pay attention to type (such as const, eq_ref is the best), key (whether to use the appropriate index) and Extra (avoid Usingfilesort and Usingtemporary); 3. Common optimization suggestions: avoid using functions or blurring the leading wildcards for fields, ensure the consistent field types, reasonably set the connection field index, optimize sorting and grouping operations to improve performance and reduce capital

See all articles