MySQL transaction and storage engine

One, MySQL transaction

(1) The concept of affairs

  • A transaction is a mechanism, an operation sequence, which contains a set of database operation commands, and submits or cancels operation requests to the system as a whole, that is, this set of database commands are either executed or not executed.
  • A transaction is an inseparable logical unit of work. When concurrent operations are performed on the database system, the transaction is the smallest unit of control.
  • Transactions are suitable for scenarios where multiple users are simultaneously operating database systems, such as banks, insurance companies, and securities trading systems.
  • The transaction ensures the consistency of the data through the integrity of the transaction.

Simply put, the so-called transaction, it is a sequence of operations, these operations are either executed or not executed, it is an indivisible unit of work.

(2) ACID characteristics of the transaction

ACID refers to the four characteristics of transactions in a reliable database management system (DBMS): Atomicity, Consistency, Isolation, and 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 transaction is a complete operation, and the elements of the transaction are inseparable.
  • All elements in the transaction must be committed or rolled back as a whole.
  • 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.

  • When the transaction is complete, the data must be in a consistent state.
  • Before the transaction begins, the data stored in the database is in a consistent state.
  • In the ongoing transaction, the data may be in an inconsistent state.
  • When the transaction is successfully completed, the data must be returned to a known consistent state again.

3. Isolation

  • Refers to 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.

The interaction between transactions is divided into several types, namely:
Dirty read: A transaction reads the uncommitted data of another transaction, and this data may be rolled back.
Non-repeatable read: Two identical queries within a transaction return different data. This is caused by the commit of other transaction modifications in the system during the query.
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.
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.

Mysql and transaction isolation level:

  • read uncommitted (read uncommitted data): does not solve dirty read
  • read committed (read the submitted data): can solve dirty read
  • Repeatable read (re-read read): can solve dirty read and non-repeatable read-mysql default
  • serializable: can solve dirty reads, non-repeatable reads and phantom reads—equivalent to lock tables

The default transaction processing level of mysql is repeatable read, while Oracle and SQL Server are read committed.

Transaction related query commands

Query the global transaction isolation level:

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

Insert picture description here

Query session transaction isolation level:.

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

Insert picture description here

Set the global transaction isolation level:

set global transaction isolation level read committed;

Insert picture description here

Set the session transaction isolation level:

set session transaction isolation level read committed;

Insert picture description here

4, endurance

  • After the transaction is completed, the changes made by the transaction to the database are persisted in the database and will not be rolled back.
  • Refers to whether the system fails or not, the result of transaction processing is permanent.
  • 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) Transaction control statement

1. Related sentences

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

2. Case

Create a table and add data

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','zhangsan','200');
insert into Fmoney values ('2','lisi','200');
select * from Fmoney;

Insert picture description here

Test commit transaction

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

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

Insert picture description here
Insert picture description here

Test rollback transaction

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

select * from Fmoney;

Insert picture description here

Test multiple rollbacks

begin;
update Fmoney set money= money + 100 where name='zhangsan';
select * from Fmoney;
SAVEPOINT S1;
update Fmoney set money= money - 100 where name='lisi';
select * from Fmoney;
SAVEPOINT S2;
insert into Fmoney values(3,'wangchao',500);
select * from Fmoney;

ROLLBACK TO S1;
select * from Fmoney;

Insert picture description here
Insert picture description here

(4) Use set to set the control transaction

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

Insert picture description here

If auto-commit is not turned on, all operations of mysql connected to the current session will be treated as a transaction until you enter rollback|commit; the current transaction is considered to be over. Before the end of the current transaction, the new mysql connection cannot read any operation results of the current session.
If automatic commit is turned on, mysql will treat each sql statement as a transaction, and then commit automatically.
Of course, no matter whether it is turned on or not, begin; commit|rollback; are all independent affairs.

Two, MySQL storage engine

(1) Storage engine concept

  • The data in MySQL is stored in files by a variety of different technologies. Each technology uses different storage mechanisms, indexing techniques, locking levels and ultimately provides different functions and capabilities. These different technologies and supporting functions are in MySQL Storage engine
  • The storage engine is the storage method or storage format in which MySQL stores data in the file system
  • MySQL commonly used storage engine
    • MyISAM
    • InnoDB
  • Components in the MySQL database responsible for performing actual data I/O operations
  • In the MySQL system, the storage engine is on the file system, and the data will be 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)MyISAM

1. Introduction to the features of MyISAM

  • MyISAM does not support transactions, nor does it support foreign key constraints. It supports full-text indexing. Data files and index files are stored separately
  • Fast access speed, no requirement for transaction integrity
  • MyISAM is suitable for query and insert-based applications
  • MyISAM is stored in three files on the disk. The file name and table name are the same, but the extensions are:
    • .frm file storage table structure definition
    • The extension of the data file is .MYD (MYData)
    • The extension of the index file is .MYI (MYIndex)
  • Table-level locking mode, the entire table is locked when the data is updated
  • The database blocks each other in the process of reading and writing
    • Will block the reading of user data during the data writing process
    • It will also block the user's data writing during the data reading process
  • Data is written or read separately, the speed process is faster and the resources are relatively small

2. Storage formats supported by MyIAM

Static (fixed length) tables
Static tables are 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 dynamic tables .

Dynamic tables
Dynamic tables contain variable fields and 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 fragmentation. It is necessary to periodically execute the OPTIMIZE TABLE 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

  • The company's business does not require support of affairs
  • Businesses that unilaterally read or write more data
  • MyISAM storage engine data reads and writes are frequent, not suitable for scenarios
  • Use read and write concurrent access to relatively low business
  • Businesses with relatively little data modification
  • Services that do not require very high data service consistency
  • Server hardware resources are relatively poor

(3)InnoDB

1. InnoDB features

  • Support transaction, support 4 transaction isolation levels
  • MySQL starts from version 5.5.5, the default storage engine is InnoDB
  • Read and write blocking is related to transaction isolation level
  • Can cache indexes and data very efficiently
  • Tables and primary keys are stored in clusters
  • Support partition and table space, similar to Oracle database
  • Support foreign key constraints, full-text index is not supported before 5.5, full-text index is supported after 5.5
  • Where the hardware resource requirements are still relatively high
  • Row-level locks, but full table scans will still be table-level locks, such as
    • updata table set a=1 where user like ‘%zhang%’
  • InnoDB does not save the number of rows of 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 number of rows of the saved number. What you need to pay attention to is , MyISAM also needs to scan the entire table when the count() statement contains the where condition
  • For self-growing fields, InnoDB must contain only the index of the field, but in the MyISAM table can be combined with other fields to build a composite index
  • When emptying the entire table, InnoDB deletes row by row, which is very slow, and MyISAM will rebuild the table.

2. InnoDB applicable production scenario analysis

  • Business needs support of affairs
  • Row-level locking has good adaptability to high concurrency, but you need to ensure that the query is completed through the index
  • Scenarios where business data is updated frequently
    • Such as: forums, Weibo, etc.
  • Business data consistency requirements are high
    • Bank business
  • Hardware devices have large memory, use InnoDB's better caching capabilities to improve memory utilization and reduce disk IO pressure

3. Basis for companies choosing storage engines

  • Need to consider what different core functions and application scenarios each storage engine provides
  • Supported fields and data types
    • All engines support common data types
    • But not all engines support other field types, such as binary objects
  • Locking type: different storage engines support different levels of locking
    • Table locking: MyISAM support
    • Row locking: InnoDB support
  • Index support
    • Indexing can significantly improve performance when searching and restoring data in the database
    • Different storage engines provide different indexing technologies
    • Some storage engines do not support indexes at all
  • Transaction processing support
    • Improve the reliability during the update and insertion of information to the table
    • The storage engine can be selected according to whether the enterprise business needs to support transactions

(4) View and set storage engine commands

1. Check the storage engines supported by the system

show engines;

Insert picture description here

2. View the storage engine used by the table

Method 1: View directly

show table status from 库名 where name='表名'\G;
例:
show table status from school where name='class'\G;

Insert picture description here

Method 2: Enter the database to view

use 库名;
show create table 表名\G;

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

Insert picture description here

3. Modify the storage engine

Method 1: Modify through alter table

use 库名;
alter table 表名 engine=MyISAM;

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

Insert picture description here

Method 2: Specify the default storage engine and restart the service by modifying the /etc/my.cnf configuration file.
Note: This method is only valid for the newly created tables after modifying the configuration file and restarting the mysql service. The existing tables will not be changed .

vim /etc/my.cnf
......
[mysqld]
......
default-storage-engine=INNODB

systemctl restart mysql.service

Insert picture description here
Insert picture description here

Method 3: Specify the storage engine when creating a table through 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;

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_51616026/article/details/113938219