MySQL - transaction; storage engine

 1. Transaction

MySQL transactions are mainly used to process data with a large amount of operations and high complexity. For example, in the personnel management system, if you delete a person, you need to delete 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 database operation statements constitute a transaction!

(1) In MySQL, only databases or tables that use the Innodb database engine support transactions

(2) Transaction processing can be used to maintain the integrity of the database and ensure that batches of SQL statements are either executed or not executed at all

(3) Transactions are used to manage DML statements (insert, update, delete)

Essence: A transaction is actually multiple DML statements executed successfully or failed at the same time!

(1) Four characteristics of transactions

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

Atomicity : the indivisibility of the transaction, and the indivisibility of each logical unit that makes up the transaction

Consistency : Before and after transaction execution, data integrity remains consistent

Isolation : transaction execution should not be interfered by other transactions

Durability ( Durability ): Once the transaction ends, the data is persisted to the database

[1] Atomicity : All operations in a transaction are either completed or not completed, and will not end in a certain link in the middle. If an error occurs during the execution of the transaction, it will be rolled back (Rollback) to the state before the transaction started, just like the transaction has never been executed

[2] Consistency ( Consistency ): Before the transaction starts and after the transaction ends, the integrity of the database is not destroyed. This means that the written data must fully comply with all preset rules, including data accuracy, seriality, and the subsequent database can spontaneously complete the scheduled work.

[3] Isolation ( Isolation ): The ability of the database to allow multiple concurrent transactions to read, write and modify its data at the same time. Isolation can prevent data inconsistency caused by cross-execution when multiple transactions are executed concurrently. Transaction isolation is divided into different levels, including read uncommitted (Read uncommitted), read committed (read committed), repeatable read (repeatable read) and serialization (Serializable).

[4] Persistence ( Durability ): After the transaction processing ends, the modification to the data is permanent, even if the system fails, it will not be lost.

Under the default settings of the MySQL command line, transactions are automatically committed, that is, the COMMIT operation will be executed immediately after the SQL statement is executed

So to explicitly start a transaction you must use the command

BEGIN or START TRANSACTION, or execute the command SET AUTOCOMMIT=0

BEGIN 

或 

START TRANSACTION

或者执行命令 

SET AUTOCOMMIT=0

Used to disable autocommit using the current session

1. Transaction control statement

InnoDB storage engine: Provides a set of log files for recording transactional activities

During the execution of the transaction, each DML operation will be recorded in the "log file of transactional activity"

(1) Start a transaction

BEGIN or START TRANSACTION explicitly starts a transaction;

(2) Submit the transaction

COMMIT can also use COMMIT WORK, but the two are equivalent. COMMIT commits the transaction and makes all modifications made to the database permanent

Committing a transaction will clear the log files of transactional activities and completely persist all data in the database table.

Committing a transaction marks the end of the transaction; and it is an all successful end

mysql> select * from user;
Empty set (0.00 sec)

mysql> start transaction;
Query OK, 0 rows affected (0.00 sec)

mysql> insert into user values(1,'admin');
Query OK, 1 row affected (0.00 sec)

mysql> select * from user;
+----+-------+
| id | name  |
+----+-------+
|  1 | admin |
+----+-------+
1 row in set (0.00 sec)

mysql> commit;
Query OK, 0 rows affected (0.00 sec)

mysql> select * from user;
+----+-------+
| id | name  |
+----+-------+
|  1 | admin |
+----+-------+
1 row in set (0.00 sec)

(3) Rollback the transaction (rollback can only be rolled back to the last commit point)

ROLLBACK can also use ROLLBACK WORK, but the two are equivalent. Rollback ends the user's transaction and undoes all uncommitted modifications in progress

Rolling back a transaction undoes all previous DML operations and clears the log files for transactional activities

Rolling back a transaction marks the end of the transaction. And it is the end of all failures (rolling back to the place where the transaction was committed last time)

mysql> select * from user;
Empty set (0.00 sec)

mysql> start transaction;
Query OK, 0 rows affected (0.00 sec)

mysql> insert into user values(1,'admin');
Query OK, 1 row affected (0.00 sec)

mysql> select * from user;
+----+-------+
| id | name  |
+----+-------+
|  1 | admin |
+----+-------+
1 row in set (0.00 sec)

mysql> rollback;
Query OK, 0 rows affected (0.01 sec)

mysql> select * from user;
Empty set (0.00 sec)

SAVEPOINT identifier, SAVEPOINT allows to create a savepoint in a transaction, there can be multiple SAVEPOINTs in a transaction;

RELEASE SAVEPOINT identifier deletes the savepoint of a transaction. When there is no specified savepoint, executing this statement will throw an exception;

ROLLBACK TO identifier rolls back the transaction to the mark point;

SET TRANSACTION is used to set the isolation level of the transaction. The InnoDB storage engine provides transaction isolation levels of READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, and SERIALIZABLE.

2. There are two main methods of MYSQL transaction processing:

(1) Use BEGIN, ROLLBACK, COMMIT to achieve

BEGIN begins a transaction

ROLLBACK transaction rollback

COMMIT transaction confirmation

(2) Directly use SET to change the automatic commit mode of MySQL:

SET AUTOCOMMIT=0 Disable autocommit

SET AUTOCOMMIT=1 Turn on autocommit

3. Transaction isolation (transaction isolation level)

(2) Four major isolation levels of transactions

4 transaction isolation levels

1. read uncommitted (read uncommitted content): Dirty reads, non-repeatable reads, and phantom reads are all possible.
2. Read committed ( read committed content ): Avoid dirty reads. However, non-repeatable reads and phantom reads are possible.
3. Repeatable read (repeatable read): Avoid dirty reads and non-repeatable reads, but phantom reads may occur.
4. Serializable (serializable): Avoid dirty reads and cannot be repeated read, phantom read

3 read exceptions

1. Dirty read: One transaction reads uncommitted data of another transaction, resulting in inconsistent query results

2. Non-repeatable read: One transaction reads the update data submitted by another transaction, resulting in inconsistent query results
. Inconsistent query results

Non-repeatable reading focuses on modifying a certain row record in update, and phantom reading focuses on adding or deleting record rows in the insert/delete table

To solve the problem of non-repeatable read, you only need to lock the rows that meet the conditions, and to solve the phantom read, you need to lock the table

There are 4 isolation levels between transactions and transactions

(1) Read uncommitted: read uncommitted (the lowest isolation level, read without committing a transaction)

Transaction A can read the uncommitted data of transaction B.

The problem with this isolation level is:

Dirty read phenomenon! (Dirty Read); we say that dirty data has been read

This isolation level is generally theoretical, and most database isolation levels start in the second gear!

(2) Read submitted: read committed ( can only be read after submission)

Transaction A can only read the data after transaction B commits

This isolation level solves the phenomenon of dirty reading

This isolation level cannot read data repeatedly

After the transaction is started, the data read for the first time is 3, and the current transaction is not over yet, maybe when the second time is read, the data read is 4

This isolation level is relatively real data, and the data read every time is absolutely real

The default isolation level of the oracle database is: read committed

(3) Repeatable read: repeatable read ( you can't read it after submitting it, and you will always read the data when you just started the transaction)

After transaction A is opened, no matter how long it takes, the data read in transaction A is consistent every time. Even though transaction B has modified and committed the data, the data read by transaction A has not changed, which is repeatable reading

Repeatable read solves non-repeatable read data

Phantom reads occur in repeatable reads. Every data read is an illusion. Not real enough!

The default transaction isolation level in mysql is repeatable read

(4) Serialization/serialization: serializable (the highest isolation level)

This is the highest isolation level and the least efficient. solved all problems

This isolation level means that transactions are queued and cannot be concurrent! Similar to synchronized, thread synchronization (transaction synchronization)

The data read every time is the most authentic, and the efficiency is the lowest

Transaction isolation level testing

View the current isolation level at the session level

mysql> SELECT @@tx_isolation;

或:

mysql> SELECT @@session.tx_isolation;

View the current isolation level at the global level

mysql> SELECT @@global.tx_isolation;

The default isolation level in MySQL is REPEATABLE-READ

mysql> select @@tx_isolation;
+-----------------+
| @@tx_isolation  |
+-----------------+
| REPEATABLE-READ |
+-----------------+
1 row in set, 1 warning (0.00 sec)

mysql> select @@session.tx_isolation;
+------------------------+
| @@session.tx_isolation |
+------------------------+
| REPEATABLE-READ        |
+------------------------+
1 row in set, 1 warning (0.00 sec)

mysql> select @@global.tx_isolation;
+-----------------------+
| @@global.tx_isolation |
+-----------------------+
| REPEATABLE-READ       |
+-----------------------+
1 row in set, 1 warning (0.00 sec)

Modify transaction isolation level

set global transaction isolation level 隔离级别;

如:

set global transaction isolation level read uncommitted;

Taking the user table as an example, two DOS command windows are opened at the same time;

After each modification of the isolation level, exit out of MySQL and re-enter

(1) read uncommitted         read uncommitted

验证:read uncommited
mysql> set global transaction isolation level read uncommitted;

事务A			        事务B
-----------------------------------------------------------
use mydb;
					    use mydb;
start transaction;
select * from user;
						start transaction;
						insert into user values('admin');
select * from user;
//此时事务B没有提交,查询事务A中就已经有数据

(2) read committed         read committed


验证:read committed
mysql> set global transaction isolation level read committed;

事务A					事务B
-------------------------------------------------------
use mydb;
						use mydb;
start transaction;
						start transaction;
select * from user;
						insert into user values('admin');
select * from user;
						commit;
select * from user;
//事务B提交之后,查询事务A中才有数据

(3) repeatable read         repeatable read

验证:repeatable read
mysql> set global transaction isolation level repeatable read;

事务A					    事务B
--------------------------------------------------------------------------------
use mydb;
							use mydb;
start transaction;
							start transaction;
//假设此时事务A中只有一条数据
select * from user;
							insert into user values('admin');
							commit;
                            select * from user;
                            //事务B中插入很多条数据,或者删除数据
select * from user;
//事务A中查看依然只有一条数据

Transaction A queries only one piece of data before operating the data in transaction B, and then no matter insert or delete in transaction B, after commit submission, there will always be one piece of data in transaction A

(4) serializable         serialization / serialization

验证:serializable
mysql> set global transaction isolation level serializable;

事务A							  事务B
----------------------------------------------------
use mydb;
								  use mydb;
start transaction;
								  start transaction;
select * from user;
insert into user values('admin');
								  select * from t_user;
                                  //此时光标一直停留在此处,等待事务A的结束
commit;
//如果此时事务A提交了,             则事务B立马返回查询结果
 

At this time, the DOS window cursor in transaction B stays here, waiting for the end of transaction A 

If transaction A commits at this time, transaction B returns the query result immediately 

(3) Seven communication behaviors of affairs 

1. PROPAGATION_REQUIRED : If there is no transaction currently, create a new transaction, if there is a transaction currently, join the transaction, this setting is the most commonly used setting

2. PROPAGATION_NESTED : If there is a current transaction, it will be executed in a nested transaction. If there is no transaction currently, do something similar to PROPAGATION_REQUIRED

3. PROPAGATION_SUPPORTS : Support the current transaction, if there is a transaction currently, join the transaction, if there is no transaction currently, execute it as a non-transaction

4. PROPAGATION_MANDATORY : support the current transaction, if there is a transaction currently, join the transaction, if there is no transaction currently, throw an exception

5. PROPAGATION_REQUIRES_NEW : support current transaction, create new transaction, no matter whether there is current transaction or not, create new transaction

6. PROPAGATION_NOT_SUPPORTED : Perform operations in a non-transactional manner. If there is a current transaction, suspend the current transaction

7. PROPAGATION_NEVER : Execute in a non-transactional manner, if there is a current transaction, an exception will be thrown

2. Storage engine

1. Storage engine

The storage engine is the underlying software organization of the database, and the database management system (DBMS) uses the data engine to create, query, update, and delete data. Different storage engines provide different storage mechanisms, indexing techniques, locking levels and other functions, and specific functions can also be obtained by using different storage engines. Many different database management systems now support many different data engines.

Storage engine is a unique term in MySQL, not in other databases. (Oracle has, but not called this name)

2. View storage engine commands

 show engines \G

Output nine engines

mysql> show engines \G;
*************************** 1. row ***************************
      Engine: InnoDB
     Support: DEFAULT
     Comment: Supports transactions, row-level locking, and foreign keys
Transactions: YES
          XA: YES
  Savepoints: YES
*************************** 2. row ***************************
      Engine: MRG_MYISAM
     Support: YES
     Comment: Collection of identical MyISAM tables
Transactions: NO
          XA: NO
  Savepoints: NO
*************************** 3. row ***************************
      Engine: MEMORY
     Support: YES
     Comment: Hash based, stored in memory, useful for temporary tables
Transactions: NO
          XA: NO
  Savepoints: NO
*************************** 4. row ***************************
      Engine: BLACKHOLE
     Support: YES
     Comment: /dev/null storage engine (anything you write to it disappears)
Transactions: NO
          XA: NO
  Savepoints: NO
*************************** 5. row ***************************
      Engine: MyISAM
     Support: YES
     Comment: MyISAM storage engine
Transactions: NO
          XA: NO
  Savepoints: NO
*************************** 6. row ***************************
      Engine: CSV
     Support: YES
     Comment: CSV storage engine
Transactions: NO
          XA: NO
  Savepoints: NO
*************************** 7. row ***************************
      Engine: ARCHIVE
     Support: YES
     Comment: Archive storage engine
Transactions: NO
          XA: NO
  Savepoints: NO
*************************** 8. row ***************************
      Engine: PERFORMANCE_SCHEMA
     Support: YES
     Comment: Performance Schema
Transactions: NO
          XA: NO
  Savepoints: NO
*************************** 9. row ***************************
      Engine: FEDERATED
     Support: NO
     Comment: Federated MySQL storage engine
Transactions: NULL
          XA: NULL
  Savepoints: NULL
9 rows in set (0.00 sec)

 Different mysql versions support different situations; nine storage engines are supported, and 5.5.36 supports eight

3. Specify the engine for table creation

//建表时指定存储引擎,以及字符编码方式。

	create table table表名(
		id int primary key,
		name varchar(255)
	)engine=InnoDB default charset=utf8;

ENGINE to specify the storage engine
CHARSET to specify the character encoding method of this table 

The default storage engine of mysql is: InnoDB
The default character encoding method of mysql is: utf8

4. Commonly used engines in MySQL

(1) MyISAM storage engine

MyISAM is based on the ISAM storage engine and extends it. It is one of the most commonly used storage engines in web, data warehousing and other application environments. MyISAM has a high insertion and query speed, but does not support transactions or foreign keys.

The tables it manages have the following characteristics:
        Three files are used to represent each table:
            format file—stores the definition of the table structure (mytable.frm)
            data file—stores the content of table rows (mytable.MYD)
            index file—stores the indexes on the table (mytable.MYI): The index is a directory of a book, a mechanism to narrow the scanning range and improve query efficiency.
        Can be converted to a compressed, read-only table to save space

Note:

For a table, as long as it is a primary key, or an index is automatically created on a field with a unique constraint

Features of MyISAM storage engine:
[1] It can be converted into a compressed, read-only table to save space
[2] MyISAM does not support transaction mechanism and has low security.

(2) InnoDB storage engine

After MySQL5.5, the InnoDB storage engine is used by default

InnoDB supports transactions and supports automatic recovery mechanism after database crash.
The main feature of InnoDB storage engine is: very safe

The tables it manages have the following main characteristics:
        – Each InnoDB table is represented in the database directory as a .frm format file
        – InnoDB table space tablespace is used to store the content of the table (table space is a logical name. Table space stores data + index .)

        – Provide a set of log files for recording transactional activities
        – Support transaction processing with COMMIT (commit), SAVEPOINT and ROLLBACK (rollback)
        – Provide full ACID compatibility
        – Provide automatic recovery after MySQL server crashes
        – Multi-version (MVCC) and row-level locking
        – supports foreign keys and referential integrity, including cascading deletes and updates

The biggest feature of InnoDB is to support transactions:
        to ensure data security.

        The efficiency is not very high, and it cannot be compressed, cannot be converted to read-only, and cannot save storage space very well.

(3) MEMORY storage engine

The data of the table using the MEMORY storage engine is stored in memory, and the length of the row is fixed.
    These two characteristics make the MEMORY storage engine very fast.

Tables managed by the MEMORY storage engine have the following characteristics:
        – Within the database catalog, each table is represented by a file in .frm format.
        – Table data and indexes are stored in memory. (The purpose is fast, fast query!)
        – Table-level lock mechanism.
        – Cannot contain TEXT or BLOB fields.

The MEMORY storage engine was formerly known as the HEAP engine.

Advantages of the MEMORY engine: The query efficiency is the highest. There is no need to interact with the hard disk.
Disadvantages of the MEMORY engine: it is not safe, and the data disappears after shutdown. Because the data and index are in the memory,
the memory is directly fetched; the speed of light and current; the hard disk is a mechanical behavior, and the data is read frame by frame

The difference is as follows:

Guess you like

Origin blog.csdn.net/MinggeQingchun/article/details/122366499