MySQL transaction and storage engine

One, MySQL transaction

1. The concept of affairs

(1) A transaction is a mechanism, an operation sequence, which contains a group of database operation commands, and all the commands as a whole are submitted or cancelled to the system, that is, this group of database commands are either executed or none carried out.
(2) A transaction is an inseparable logical unit of work. When concurrent operations are performed on the database system, the transaction is the smallest control unit.
(3) Transactions are suitable for scenarios where multiple users are simultaneously operating database systems, such as banks, insurance companies, and securities trading systems.
(4) The transaction ensures the consistency of data through the integrity of the transaction.

2. ACID characteristics of transactions

Note: ACID refers to the four characteristics of transactions in a reliable database management system (DBMS): Atomicity, Consistency, Isolation, Durability . These are several characteristics that a reliable database should have.
(1) Atomicity: Refers to the transaction as an indivisible unit of work, and the operations in the transaction either all happen or never happen.
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: It means that the integrity constraints of the database have not been destroyed before the start of the transaction and after the end of the transaction.
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 the ongoing transaction, the data may be in an inconsistent state.
d. When the transaction is successfully completed, the data must be returned to a known consistent state again.
(3) Isolation: In a concurrent environment, when different transactions manipulate the same data at the same time, each transaction has its own complete data space.
All concurrent transactions that modify data are isolated from each other, indicating that the transaction must be independent, and it should not depend on or affect other transactions in any way.
A transaction that modifies data can access the data before another transaction using the same data starts, or after another transaction using the same data ends.
(4) Persistence: After the transaction is completed, the changes made to the database by the transaction are persisted in the database and will not be rolled back.
a. It means that regardless of whether the system fails, the result of transaction processing is permanent.
b. Once the transaction is committed, the effect 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 goal, and persistence is the result.

3. Interaction between things

Classification
(1), dirty read: A transaction reads uncommitted data of another transaction, and this data may be rolled back.
(2) Non-repeatable read: Two identical queries in a transaction return different data. This is caused by the commit of other transaction modifications in the system during the query.
(3), phantom read: A transaction modifies the data in a table, and this modification involves all data rows in the table. At the same time, another transaction also modifies the data in this table. This modification is to insert a new row of data into the table. Then, the user operating the previous transaction will find that there are still unmodified data rows in the table, as if an illusion occurred.
(4) Lost update: Two transactions read the same record at the same time. A first modifies the record, and B also modifies the record (B does not know that A has modified it). After B submits the data, the modification result of B overwrites the modification result of A.

4. Mysql and transaction isolation level

(1), read uncommitted: read uncommitted data, do not solve dirty reads
(2), read committed: read submitted data, can solve dirty reads
(3), repeatable read: reread reads, can be solved Dirty read and non-repeatable read-------------mysql default
(4), serializable: serialization, can solve dirty read, non-repeatable read and virtual read--------- ------- Equivalent to lock table
Note: MySQL's default transaction processing level is repeatable read, while Oracle and SQL Server are read committed to
Insert picture description here
query the global transaction isolation level:

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

Query session transaction isolation level:

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

Set the global transaction isolation level:

set global transaction isolation level read committed;

Set the session transaction isolation level:

set session transaction isolation level read committed;

5. Transaction control statement

BEGIN 或 START TRANSACTION:显式地开启一个事务。
COMMIT 或 COMMITWORK:提交事务,并使已对数据库进行的所有修改变为永久性的。
ROLLBACK 或 ROLLBACKWORK:回滚回结束用户的事务,并撤销正在进行的所有未提交的修改。
SAVEPOINT S1:使用 SAVEPOINT 允许在事务中创建一个回滚点, 一个事务中可以有多个SAVEPOINT;“S1"代表回滚点名称。
ROLLBACK TO [SAVEPOINT] S1:把事务回滚到标记点。

Example:

use edg;
create table account (
id int(10) primary key not null,
name varchar(40),
money double 
);

insert into account values(1,'A',1000);
insert into account values(2,'B',1000);

#测试提交事务
begin;
update account set money= money - 1000000 where name='A';
commit;
quit

mysql -u root -p
use edg;
select * from account;

#测试回滚事务
begin;
update account set money= money + 1000000 where name='A';
rollback;
mysql -u root -P
use edg;
select * from account;

#测试多点回滚
begin;
update account set money= money + 1000000 where name='A';
SAVEPOINT S1;
update account set money= money + 1000000 where name='B';
SAVEPOINT S2;
insert into account values(3,'C',1000);

select * from account;
ROLLBACK TO S1;
select * from account

6. Use set to set the control transaction

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

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

Two, MySQL storage engine

1. Introduction to storage engine concept

(1) The data in MySQL is stored in files using a variety of different technologies. Each technology uses different storage mechanisms, indexing techniques, and locking levels, and ultimately provides different functions and capabilities. These different technologies and supporting facilities The function of is called the storage engine in MySQL.
(2) Storage engine is the storage method or storage format of MySQL storing data in the file system
(3) MySQL commonly used storage engines are:
a, MylSAM
b, InnoDB
(4) MySQL database components, responsible for executing the actual data I/O operation
(5) In the MySQL system, the storage engine is above the file system, and the data is transferred to the storage engine before being saved to the data file, and then stored according to the storage format of each storage engine.

2. Introduction to the features of MyISAM

(1) MyISAM does not support transactions or foreign key constraints. It only supports full-text indexing. Data files and index files are stored separately.
(2) The access speed is fast and there is no requirement for transaction integrity.
(3) MyISAM is suitable for query and insertion The main application
(4) MylSAM is stored in three files on the disk, the file name and table name are the same, but the extensions are:
a, frm file storage table structure definition
b, the extension of the data file is .MYD ( MYData)
c. The extension of the index file is .MYI (MYIndex)
(5) Table-level locking form, the entire table is locked when the data is updated
(6) The database blocks each other in the process of reading and writing
a. It will be in the process of data writing reading the block user data
B, will block user data is written during the read data
7, data is written or read separately, the process speed faster and relatively small footprint
8, MyIAM storage format supported by
a , Static table
b, dynamic table
c, compressed table
Note:
Static table (fixed length): Static table is the default storage format. The fields in the static table are all non-variable fields, so that each record has a fixed length. The advantage of this storage method is that the storage is very fast, easy to cache, and easy to recover from failure; the disadvantage is that it usually takes up more space than the dynamic table .
Dynamic table: The dynamic table contains variable fields, and the records are not of fixed length. The advantage of this storage is that it takes up less space, but frequent updates and deletions of records will generate fragments. It is necessary to periodically execute the OPTIMIZETABLE statement or the myisamchk -r command to improve performance , And it is relatively difficult to recover when a failure occurs.
Compressed table: The compressed table is created by the myisamchk tool and occupies a very small space. Because each record is compressed separately, there is only a very small access cost.

3. Examples of production scenarios applicable to MyISAM

(1) The company's business does not require transaction support
(2) The business that reads or writes more data unilaterally
(3) MylSAM storage engine data reads and writes are frequently read and write scenarios are not suitable
(4) Use read and write concurrent access relatively Low business
(5) Business with relatively few data modifications
(6) Business with not very high data business consistency requirements
(7) Relatively poor server hardware resources

4. InnoDB features introduction

(1) Support transactions, support 4 transaction isolation levels
(2) MySQL starts from version 5.5.5, the default storage engine is InnoDB
(3) Read and write blocking is related to transaction isolation level
(4) Can cache indexes and caches very efficiently Data
(5) Tables and primary keys are stored in clusters
(6) Support partitions and table spaces, similar to oracle databases
(7) Support foreign key constraints, before 5.5, full-text indexes are not supported, and after 5.5, full-text indexes are supported
(8) For hardware resources The requirements are still relatively high
(9) row-level locking, but the full table scan will still be table-level locking,

update table set a=1 where user like '%yun%';

(10) InnoDB does not save the number of rows in the table, such as select count( ) from table;, InnoDB needs to scan the entire table to calculate how many rows there are, but MyISAM simply reads the saved number of rows. It should be noted that MyISAM also needs to scan the entire table when the count( ) statement contains the where condition
(11) For self-growing fields, InnoDB must contain an index with only this field, but it can be created with other fields in the MyISAM table When the composite index
(12) empties the entire table, InnoDB deletes row by row, which is very slow. MyISAM will rebuild the table.

5. InnoDB applicable production scenario analysis

(1) Business needs transaction support
(2) Row-level locking has a good ability to adapt to high concurrency, but it is necessary to ensure that the query is completed through the index
(3) Scenarios
where business data is updated frequently, such as: forums, microblogs, etc.
(4) Business data consistency requirements are high,
such as: banking business
(5) Hardware equipment has a large memory, use InnoDB's better caching capabilities to improve memory utilization and reduce disk IO pressure

6. The basis for enterprises to choose storage engines

(1) Need to consider what different core functions and application scenarios each storage engine provides
(2) Supported fields and data types
a, all engines support common data types
b, but not all engines support others Types of fields, such as binary objects
(3) Locking types: different storage engines support different levels of locking
a, table locking: MyISAM support
b, row locking: InnoDB support
(4) index support
a, indexing in search and recovery Data in the database can significantly improve performance
b. Different storage engines provide different index creation techniques
c. Some storage engines do not support indexes at all.
(5) Transaction processing support
a. Improve the update and insert information in the table Reliability during the period
b. The storage engine can be selected according to whether the business needs to support transactions

7. Related commands

#查看系统支持的存储引擎
show engines;

#查看表使用的存储引擎
方法一-:
show table status from 库名 where name='表名'\g

方法二:
use 库名;
show create table 表名;

#修改存储引擎
1.通过 alter table修改
use 库名;
alter table 表名 engine=MyISAM;

2.通过修改 /etc/my.cnf 配置文件,指定默认存储引擎并重启服务
vim /etc/my.cnf 
.......
[mysqld]
.......
default-storage-engine=INNODB

systemctl restart mysql.service
注意:此方法只对修改了配置文件并重启mysq1服务后新创建的表有效,已经存在的表不会有变更。

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

Guess you like

Origin blog.csdn.net/tefuiryy/article/details/113657864