MySQL----things and storage engines

1. Business introduction

1.1 The concept of MySQL transaction

A transaction is a mechanism, an operation sequence, which includes a set of database operation commands (addition, deletion, modification), and submits or revokes the operation request to the system together with all the commands as a whole, that is, this set of database commands is either executed or executed. None are executed.

A transaction is an indivisible logical unit of work. When performing concurrent operations on a database system, a transaction is the smallest control unit. Transactions ensure data consistency through the integrity of transactions. Transactions improve reliability during updates and inserts into tables.

Transactions are suitable for scenarios where multiple users operate database systems at the same time, such as banks, insurance companies, and securities trading systems.

Generally speaking, the so-called transaction is a sequence of operations. These operations (addition, deletion, modification) are either executed or not executed. It is an indivisible unit of work.

1.2 ACID characteristics of transactions

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

atomicity

It means that a transaction is an indivisible unit of work, and the operations in the transaction either all occur or none occur.

A transaction is a complete operation, and the elements of a transaction are inseparable. All elements in a transaction must be committed or rolled back as a whole. If any element in the transaction fails, the entire transaction fails.

consistency

It means that the integrity constraints of the database are not violated before the transaction starts and after the transaction ends.

When the transaction completes, the data must be in a consistent state. Before a transaction starts, the data stored in the database is in a consistent state. During an ongoing transaction, data may be in an inconsistent state. When the transaction completes successfully, the data must come back to a known consistent state again.

isolation

It means that 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 a transaction must be independent, 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 begins, or after another transaction using the same data ends.

That is to say, when accessing the database concurrently, a user's transaction will not be interfered by other transactions, and the database between concurrent transactions is independent.

Persistence

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.

It means that regardless of whether the system fails or not, the results of transaction processing are permanent. Once a transaction is committed, the effects of the transaction are permanently retained in the database.

1.3 Interaction between transactions

Consistency issues that may occur at different isolation levels when multiple concurrent transactions agree to give table data:

  • 脏读: A transaction reads uncommitted data of another transaction, and this data may be rolled back.
  • 不可重复读: Two identical queries within a transaction return different data. This is caused by the commits modified by other transactions in the system at the time of the query.
  • 幻读: Two queries in one transaction will see data inconsistency (it may be that data that was not found before), this situation may be because other transactions have inserted new data and submitted it during the two query processes.
  • 丢失更新: A transaction modifying data and committing may overwrite data modified and committed by another transaction.

isolation level

level meaning dirty read non-repeatable read phantom read
Uncommitted read:Read Uncommitted (RU) Dirty reads are allowed, that is, allowing a transaction to see uncommitted modifications of other transactions. allow allow allow
Commit read:Read Committed(RC) A transaction is allowed to only see the modifications that have been committed by other transactions, and the uncommitted modifications are not visible. not allowed allow allow
Reread reads:Repeatable Read(RR) Mysql's default isolation level ensures that if you execute the same SELECT statement twice in a transaction, you can get the same result, regardless of whether other transactions commit these modifications not allowed not allowed disallowed for InnoDB, allowed conditionally
Serial read:Serializable Fully serialized reads completely isolate one transaction from other transactions. Every time you read, you need to obtain a table-level shared lock, and reading and writing will block each other. Will reduce the efficiency of the database. not allowed not allowed not allowed

1.4 Set the isolation level

There are two scopes of transaction isolation levels:
● Global level: valid for all sessions
● Session level: valid only for the current session

Query the global transaction isolation level:
show global variables like '%isolation%';
SELECT @@global.tx_isolation;

insert image description here

Query session transaction isolation level:
show session variables like '%isolation%';
SELECT @@session.tx_isolation;
SELECT @@tx_isolation;

insert image description here

Set the global transaction isolation level:
set global transaction isolation level read committed;
set @@global.tx_isolation='read-committed'; #Invalid after restarting the service

insert image description here

Set session transaction isolation level:
set session transaction isolation level repeatable read;
set @@session.tx_isolation='repeatable-read';

insert image description here

1.5 Transaction Control Statements

BEGIN or START TRANSACTION: Explicitly start a transaction.
COMMIT or COMMIT WORK: Commits the transaction and makes all changes made to the database permanent.
ROLLBACK or ROLLBACK WORK: Rollback ends the user's transaction and undoes any ongoing uncommitted modifications.
SAVEPOINT S1: Use SAVEPOINT to allow creating a rollback point in a transaction, and there can be multiple SAVEPOINTs in a transaction; "S1" represents the name of the rollback point.
ROLLBACK TO [SAVEPOINT] S1: Roll back the transaction to the mark point.

Example:
1. Test commit transaction
insert image description here

2. Test rollback transaction

insert image description here

3. Test multi-point rollback

insert image description here

1.6 Use set settings to control transactions

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

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

use kgc;
select * from account;
SET AUTOCOMMIT=0;
update account set money= money + 100 where name='B';
select * from account;
quit

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

insert image description here

insert image description here

2. Storage engine introduction

MyISAM tables support 3 different storage formats:
(1) 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 is of fixed length. The advantage of this storage method is that it is stored very quickly, easy to cache, and easy to recover when a failure occurs; the disadvantage is that it usually takes up more space than a dynamic table .

(2) Dynamic table The dynamic
table contains variable fields, and the records are not of fixed length. The advantage of such storage is that it takes up less space, but frequent updates and deletions of records will cause fragmentation. It is necessary to execute the OPTIMIZE TABLE statement or the myisamchk -r command regularly To improve performance, and it is relatively difficult to recover when a failure occurs.

(3) Compressed table
The compressed table is created by the myisamchk tool and occupies a very small space, because each record is compressed individually, so there is only a very small access cost.

Commonly used storage engines: InnoDB, MyISAM
MyISAM: does not support transactions and foreign key constraints, occupies less resources, fast access speed, table-level locking, supports full-text indexing, and is suitable for application scenarios that do not require transaction processing, separate writing or querying.
InnoDB: supports transaction processing, foreign key constraints, good caching capabilities, row-level locking, and good read and write concurrency. After version 5.5, it supports full-text indexing, and is suitable for application scenarios with high consistency requirements and frequent data updates.

2.1 View the storage engines supported by the system

show engines;

insert image description here

#Check the storage engine used by the table
Method 1:
show table status from library name where name='table name'\G

insert image description here

Method 2:
use library name;
show create table table name;

insert image description here

2.2 Modify the storage engine

1.
Modify the use library name through alter table ;
alter table table name engine=MyISAM;

insert image description here

2. By modifying the /etc/my.cnf configuration file, specify the default storage engine and restart the service
vim /etc/my.cnf
...
[mysqld]
...
default-storage-engine=INNODB

systemctl restart mysql.service
Note: This method is only valid for newly created tables after modifying the configuration file and restarting the mysql service. Existing tables will not be changed.

insert image description here

3.
Specify the storage engine use library name when creating a table through create table ;
create table table name (field 1 data type,...) engine=MyISAM;

insert image description here

2.3 The relationship between InnoDB row locks and indexes

InnoDB row locks are implemented by locking index items. If there is no index, InnoDB will lock records through hidden clustered indexes.

1)
delete from t1 where id=1;
if the id field is the primary key, and InnoDB uses a clustered index for the primary key, it will directly lock the entire row of records.

2)
delete from t1 where name='aaa';
If the name field is an ordinary index, it will lock the two rows of the index first, and then lock the record corresponding to the corresponding primary key.

3)
delete from t1 where age=23;
If the age field has no index, it will scan and filter the entire table, and each record on the table will be locked.

//Deadlock
Deadlock is generally caused by transactions waiting for each other's resources, and finally forming a loop.

Example:

insert image description here

Open two virtual machines

Virtual machine one:

insert image description here

Virtual machine two:

insert image description here

for update can take an exclusive lock on a row in the database. While one transaction's operations are pending, other transactions can read but not write or update.
#Shared lock: Also called read lock, when the user wants to read data, a shared lock is added to the data, and multiple shared locks can be added at the same time.
#Exclusive lock: It is also called a write lock. When the user wants to write data, an exclusive lock is added to the data. Only one exclusive lock can be added. It is mutually exclusive with other exclusive locks and shared locks.

// How to avoid deadlock as much as possible?
1) Use more reasonable business logic to access tables and rows in a fixed order.
2) Dismantle big affairs into small ones. Large transactions are more prone to deadlocks. If the business permits, large transactions should be split into small ones.
3) In the same transaction, try to lock all the resources needed at once to reduce the probability of deadlock.
4) Lower the isolation level. If the business permits, lowering the isolation level is also a better choice. For example, adjusting the isolation level from RR to RC can avoid many deadlocks caused by gap locks.
5) Add reasonable indexes to the table. If no index is used, a lock will be added to each row of the table, and the probability of deadlock will be greatly increased.

Guess you like

Origin blog.csdn.net/weixin_51728919/article/details/131234024