MySQL storage engine, database building, authority management

Table of contents

I. Introduction

1. Introduction to MySQL

2. Storage engine

1. What is a storage engine

         2. Common storage engines

2.1.InnoDB (MySQL default engine)

2.1.1. Four isolation levels

2.2. MyISAM storage engine

2.3. Memory storage engine

3. ACID transactions

Three, CRUD operation

1. Insert data

2. Query data

3. Modify data

4. Delete data

4. Database

1. Introduction to the default database

2. Create a database

3. View library

4. Delete library

5. User

0. Preface

1. Create a user

change Password

2. View users

3. User empowerment

4. Take back user rights

5. View user permissions

6. Delete user



I. Introduction

1. Introduction to MySQL

MySQL is an open source relational database management system (RDBMS) widely used for web application development and data storage. Here are some details about MySQL:

                1. Relational database management system : MySQL is a relational database management system that uses tables to organize and store data. It supports data management and query using SQL (Structured Query Language).

                2. Open source and free : MySQL is open source software, and the code can be obtained and used for free. This makes it one of the very popular choices for developers and businesses alike.

                3. Cross-platform support : MySQL can run on multiple operating systems, including Windows, Linux, macOS, etc. This makes it very flexible and adaptable to various environments.

                4. High performance and scalability : MySQL is known for its high performance and can handle a large number of simultaneous access requests. It supports concurrent processing and multithreading, and can easily scale to large datasets and high-traffic applications.

                5. Security : MySQL provides various security features, such as user authentication, authority management, and data encryption. It protects data from unauthorized access and malicious attacks.

                6. Data integrity : MySQL supports various constraints, such as primary key, unique constraint, foreign key, etc., to ensure data integrity and consistency.

                7. Backup and recovery : MySQL provides backup and recovery tools, which can regularly back up the database and easily restore the data when needed.

                8. Multiple storage engines : MySQL supports multiple storage engines, such as InnoDB, MyISAM, etc. Each storage engine has different features and advantages, and the appropriate storage engine can be selected according to the needs of the application.

                9. Support replication and high availability : MySQL supports master-slave replication and cluster technology, which can realize data replication and high availability, and improve system reliability and availability.

                10. Customizability : MySQL is a modular system that users can customize according to their needs. It provides a rich plug-in and extension mechanism, enabling developers to add new functions and features as needed.

In short, MySQL is a powerful, high-performance, reliable and secure relational database management system for applications of all sizes and types. It is widely used and recognized in the field of web development and data storage.

2. Storage engine

1. What is a storage engine

The database 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. Using different storage engines, you can also obtain specific functions. Many different database management systems now support many different data engines. The core of MySQL is the storage engine .

MySQL provides several different storage engines, including those that handle transaction-safe tables and those that handle non-transaction-safe tables. In MySQL, it is not necessary to use the same storage engine in the entire server. According to specific requirements, different storage engines can be used for each table.

MySQL 8.0 supports multiple storage engines, the following are some common storage engines :

  1. InnoDB : The default storage engine, supports transaction processing and row-level locking, and has good data integrity and concurrency performance.

  2. MyISAM : The most commonly used non-transactional storage engine, suitable for application scenarios with frequent reads and few writes.

  3. Memory : Also known as Heap, stores data in memory and is suitable for temporary data or cache that requires fast read and write operations. Transactions and persistence are not supported.

  4. NDB Cluster : Suitable for high availability and distributed applications, providing the function of distributing data to multiple servers.

In addition, MySQL 8.0 also supports other storage engines, such as Archive, CSV, Blackhole, etc. Each storage engine has different characteristics and applicable scenarios. When selecting a storage engine, factors such as data access patterns, requirements, and performance requirements should be considered. By default, the InnoDB storage engine is recommended, but the specific choice should be evaluated and decided based on actual needs.

2. Common storage engines

2.1.InnoDB (MySQL default engine)

InnoDB is a transactional storage engine that provides support for database ACID transactions, and implements four isolation levels of the SQL standard , with row-level locking (this shows that the granularity of the lock is small, and there is no need to lock the entire table, so it is suitable for high concurrency) and foreign key support (the only one of all database engines, only it supports foreign keys). The design goal of this engine is to handle large-capacity data database systems. Create a buffer pool in memory for caching data and indexes.

InnoDB is the engine of choice for transactional databases, supports transaction-safe tables (ACID), and supports row locking and foreign keys. InnoDB is the default MySQL engine .

Tips:

Row Locking (Row Locking): refers to the locking of individual data rows in the database , rather than locking the entire table or other larger granularity. When a row lock is applied to a data row, other transactions cannot modify or delete the data row until the transaction holding the lock releases the lock .

The main advantage of row locking is that it can provide better concurrency performance and more fine-grained lock control. Multiple transactions can access different rows of data concurrently without blocking each other . This is very important for database environments with high concurrent read and write operations.

2.1.1. Four isolation levels

1. Read Uncommitted (Read Uncommitted) : At this isolation level, all transactions can see the execution results of other uncommitted transactions. This isolation level is rarely used in practical applications, because its performance is not much better than other levels. Read uncommitted data, also known as dirty read (Dirty Read)

2. Read Committed (Read Committed) : This is the default isolation level of most database systems (but not MySQL's default). It satisfies the simple definition of isolation: a transaction can only see changes made by committed transactions. This isolation level also supports the so-called non-repeatable read (NonrepeatableRead), because other instances of the same transaction may have new commits during the processing of this instance, so the same select may return different results

3. Repeatable Read (Repeatable Read) : This is the default transaction isolation level of MySQL. When multiple instances of the same transaction read data concurrently, they will see the same data. But in theory, this can lead to another thorny problem: phantom read (Phantom Read). Simply put, phantom reading means that when a user reads a range of data rows, another transaction inserts a new row in the range. When the user reads the range of data rows again, it will find that there are new Phantom" line.

4. Serializable (Serializable) : This is the highest isolation level, which solves the problem of phantom reading by forcing transactions to be sorted so that they cannot conflict with each other. In short, it adds a shared lock on each data row read. At this level, a large number of timeouts and lock contention may result

isolation level dirty read non-repeatable read Phantom reading
Read Uncommitted possible possible possible
Read Committed impossible possible possible
Repeatable Read impossible impossible possible
Serializable impossible impossible impossible

Tips:

What are dirty reads, non-repeatable reads, and phantom reads?

  • dirty read

Dirty reading means that when a transaction is accessing data and modifying the data, but this modification has not been submitted to the database, at this time, another transaction also accesses the data and then uses the data.

At T2, transaction B changed the original data of Zhang San's score from 80 to 70, and then it was read by transaction A at T3, but transaction B was abnormal at T4, and a rollback operation was performed. In this process, we call 70 dirty data, and transaction A has performed a dirty read.

  • non-repeatable read

Non-repeatable read, sometimes referred to as "read committed". What does it mean, that is, within a transaction, the same data is read multiple times, but different results are returned. In fact, this is because during the period of reading data in the transaction interval, other transactions have modified this piece of data and have committed it, and non-repeatable read accidents will occur.

In the figure, transaction A queries the same statement at T1 and T4, but gets different results. This is because transaction B modifies the data at T2~T3 and submits it. In this process, the data read twice in one transaction is different, which we call non-repeatable read.

The difference between non-repeatable read and dirty read : the former is "read committed", the latter is "read uncommitted"

  • Phantom reading

Phantom reading refers to a hallucination-like phenomenon that occurs when a transaction is not executed independently, inserting or deleting data currently affected by another transaction. For example, when a certain transaction checks the count of data in the table, it is 10, and after a period of time, it is 11, which causes phantom reading, and the data obtained by the previous detection is like an illusion. The reasons for phantom reads and non-repeatable reads are very similar. When the data is manipulated multiple times, the results are found to be different from the original ones, and other transaction interference occurs. However, the focus of phantom reading is to add and delete data, and the number of records obtained by operating data multiple times is different; the focus of non-repeatable reading is to modify data, and the value of data is found to be different after reading data multiple times.

Transaction B inserts a new piece of data into the table. When transaction A queries the data after time T3, it suddenly finds that there is one more item in the data than when it was queried before, like a hallucination.

2.2. MyISAM storage engine

Compared with InnoDB, it does not provide support for database transactions, and does not support fine-grained locks (row locks) and foreign keys. When inserting and updating tables, the entire table needs to be locked, so the efficiency will be lower, and it may be in high concurrency Encountered a bottleneck, but the MyIsam engine is independent of the operating system and can be used on windows and linux. However, unlike Innodb, MyIASM stores the number of rows in the table, so when SELECT COUNT(*) FROM TABLE, you only need to directly read the saved values ​​without performing a full table scan. If the table has far more read operations than write operations and does not require the support of database transactions, then MyIASM is also a good choice.

shortcoming:

  • Cannot recover data after table corruption

Applicable scene:

  • MyIsam places great emphasis on fast reading

  • The number of rows in the table is automatically stored in the MyIsam table, which can be obtained directly when needed

  • Applicable to situations that do not require transaction support, foreign key functions, and require locking of the entire table

2.3. Memory storage engine

Create a table with the contents stored in memory. Each MEMORY table actually corresponds to only one disk file. Table access of MEMORY type is very fast, because its data is placed in memory, and the HASH index is used by default. But once the service is closed, the data in the table will be lost. HEAP allows temporary tables that only reside in memory. Residing in memory makes HEAP faster than ISAM and MYISAM, but the data it manages is unstable, and if it is not saved before shutting down, all data will be lost. HEAP also does not waste a lot of space when rows are deleted. HEAP tables are useful when you need to select and manipulate data using SELECT expressions. Memory supports hash index and B-tree index at the same time. B-tree index can use partial query and wildcard query, and operators such as <,> and >= can also be used to facilitate data mining. The hash index is equal and faster, but for the range Much slower.

shortcoming:

  • The data required to be stored is in a format with constant data length, Blob and Text type data are not available (the length is not fixed)

  • Tables are deleted when they are done with

Applicable scene:

  • Those code tables whose content changes infrequently, or as intermediate result tables of statistical operations, are convenient for efficiently stacking intermediate results for analysis and obtaining final statistical results

  • The target data is relatively small, and it is accessed very frequently, and the data is stored in the memory. If the data is too large, it will cause memory overflow. The size of the Memory table can be controlled by the parameter max_heap_table_size to limit the maximum size of the Memory table

  • Data is temporary and must be immediately available, so it can be stored in memory

  • It doesn't matter if the data stored in the Memory table is lost suddenly

3. ACID transactions

  1. Atomicity : A transaction is an atomic operation unit, and the operations on the database in the transaction are either executed or not executed.

  2. Consistency (Consistency) : Before the transaction starts and after the completion, the data must be kept in a consistent state, and the integrity of the database must be guaranteed. That is, the data must conform to the rules of the database.

  3. Isolation : The execution of a transaction cannot be interfered with by other transactions. That is, the internal operations and data used by a transaction are isolated from other concurrent transactions, and the concurrently executed transactions cannot interfere with each other.

  4. Durability : Persistence also becomes permanent, which means that once a transaction is committed, its changes to the data in the database should be permanent.

Three, CRUD operation

1. Insert data

Create (Create) operation: Create operation is used to add new data records to the database. In MySQL, we can use the INSERT INTO statement to create operations.

INSERT INTO users (name, email, age) VALUES ('John', '[email protected]', 25);

2. Query data

Read (Read) operation: The read operation is used to retrieve data records from the database. In MySQL, we can use the SELECT statement for read operations.

For example, usersto retrieve all records from a table:

SELECT * FROM users;

Alternatively, usersretrieve records from a table that meet certain criteria:

SELECT * FROM users WHERE age > 18;

3. Modify data

Modify (Update) operation: The update operation is used to modify the existing data records in the database. In MySQL, we can use the UPDATE statement for update operations.

For example, to modify usersthe age of a record in a table:

UPDATE users SET age = 30 WHERE id = 1;

4. Delete data

Delete operation: The delete operation is used to delete data records from the database. In MySQL, we can use the DELETE FROM statement to delete.

For example, usersto delete records from a table that meet a certain condition:

DELETE FROM users WHERE age > 60;

4. Database

1. Introduction to the default database

  • information_schema

information_schema provides access to database metadata. (Metadata is data about data, such as the database or table name, the data type of a column, or access permissions. Other terms sometimes used to describe this information include "data dictionary" and "system catalog.") In other words Say, information_schema is an information database that holds information about all other databases maintained by the MySQL server. (such as database name, database table, data type and access rights of table columns, etc.)

  • mysql

The core database of MySQL, similar to the master table in SQL Server, is mainly responsible for storing the control and management information that MySQL itself needs to use, such as database users and user access rights. Commonly used, such as modifying the root user password in the user table of the mysql database.

  • performance_schema

Mainly used to collect database server performance parameters. And the storage engine of the table in the library is PERFORMANCE_SCHEMA, but the user cannot create a table with the storage engine of PERFORMANCE_SCHEMA. MySQL5.7 is enabled by default.

  • sys

After the installation of MySQL 8.0 is completed, there will be an additional sys database. The sys database mainly provides some views, and the data comes from performance_schema, mainly to make it easier for developers and users to view performance problems.

2. Create a database

In MySQL, you can use the CREATE DATABASE statement to create a database. The syntax is as follows:

CREATE DATABASE [IF NOT EXISTS] <数据库名>
[[DEFAULT] CHARACTER SET <字符集名>] 
[[DEFAULT] COLLATE <校对规则名>];

Content in [] is optional. The syntax is explained as follows:

  • <database name>: Create the name of the database. The MySQL data storage area will represent the MySQL database in the form of a directory, so the database name must conform to the folder naming rules of the operating system, and it cannot start with a number, and try to be as practical as possible. Note that there is no case sensitivity in MySQL.

  • IF NOT EXISTS: Judging before creating the database, the operation can only be performed if the database does not currently exist. This option can be used to avoid the error of duplicate creation of a database that already exists.

  • [DEFAULT] CHARACTER SET: Specifies the character set of the database. The purpose of specifying the character set is to avoid garbled characters in the data stored in the database. If you do not specify a character set when creating a database, the system's default character set is used.

  • [DEFAULT] COLLATE: Specifies the default collation for this database.

3. View library

In MySQL, you can use the SHOW DATABASES statement to view or display the databases within the scope of the current user's authority. The syntax for viewing the database is:

SHOW DATABASES [LIKE '数据库名'];

The syntax is explained as follows:

  • The LIKE clause is optional and is used to match the specified database name. The LIKE clause can match partially or completely.

  • The database name is surrounded by single quotes ' '.

4. Delete library

In MySQL, when you need to delete the created database, you can use the DROP DATABASE statement. Its syntax format is:

DROP DATABASE [ IF EXISTS ] <数据库名>

The syntax is explained as follows:

  • <database name>: Specify the name of the database to be deleted.

  • IF EXISTS: Used to prevent errors when the database does not exist.

  • DROP DATABASE: Delete all tables in the database and delete the database at the same time. Be very careful when using this statement to avoid deletions by mistake. If you want to use DROP DATABASE, you need to obtain the database DROP permission.

Note: After MySQL is installed, the system will automatically create two system databases named information_schema and mysql. The system database stores some information related to the database. If these two databases are deleted, MySQL will not work normally.

5. User

0. Preface

When MySQL is installed, a user named root will be created by default. This user has super authority and can control the entire MySQL server.

1. Create a user

MySQL provides the following three methods to create users.

  1. Create a user using the CREATE USER statement

  2. Add users to the mysql.user table

  3. Create users using the GRANT statement

  • Create a user using the CREATE USER statement

You can use the CREATE USER statement to create MySQL users and set corresponding passwords. Its basic syntax is as follows:

CREATE USER <用户> [ IDENTIFIED BY [ PASSWORD ] 'password' ] [ ,用户 [ IDENTIFIED BY [ PASSWORD ] 'password' ]]

The parameters are described as follows:

  1. User : Specify to create a user account, the format is user_name'@'host_name. Here user_nameis the user name, host_namewhich is the host name, that is, the name of the host used by the user to connect to MySQL.

  2. IDENTIFIED BY clause : used to specify the user password. A new user may not have an initial password. If the user does not set a password, this clause can be omitted.

  3. PASSWORD 'password' : PASSWORD indicates that the hash value is used to set the password, and this parameter is optional.

Example:

CREATE USER 'test1'@'localhost' IDENTIFIED BY 'test1';

Tips:

change Password

The SET PASSWORD statement can be used to reset the login password of other users or the password of the account used by oneself. The syntax structure of using the SET statement to modify the password is as follows:

SET PASSWORD = PASSWORD ("rootpwd");

2. View users

#切换数据库
use mysql;
#查询用户信息
select host,user,authentication_string from user;

MySQL 5.7 version no longer uses Password as the password field, but changed it to authentication_string.

Description of the host parameter value:

host column value meaning
% match all hosts
localhost localhost will not be resolved into an IP address, and it will be connected directly through UNIXsocket
127.0.0.1 It will be connected through the TCP/IP protocol and can only be accessed locally
::1 ::1 is compatible with ipv6, which means 127.0.0.1 is the same as ipv4

3. User empowerment

In MySQL, only users with GRANT authority can execute the GRANT statement, and its syntax is as follows:

GRANT priv_type [(column_list)] ON database.table
TO user [IDENTIFIED BY [PASSWORD] 'password']
[, user[IDENTIFIED BY [PASSWORD] 'password']] ...
[WITH with_option [with_option]...]

Parameter Description:

  • The priv_type parameter indicates the permission type;

  • The columns_list parameter indicates which columns the permission acts on. When this parameter is omitted, it means that it acts on the entire table;

  • database.table is used to specify the level of permissions;

  • The user parameter represents the user account, which is composed of the user name and the host name, and the format is "'username'@'hostname'";

  • The IDENTIFIED BY parameter is used to set a password for the user;

  • The password parameter is the user's new password.

The WITH keyword is followed by one or more with_option parameters. This parameter has 5 options, which are described in detail as follows:

  • GRANT OPTION: Authorized users can grant these permissions to other users;

  • MAX_QUERIES_PER_HOUR count: Set count queries per hour;

  • MAX_UPDATES_PER_HOUR count: Set to allow count updates per hour;

  • MAX_CONNECTIONS_PER_HOUR count: Set up count connections per hour;

  • MAX_USER_CONNECTIONS count: Set the count connections that a single user can have at the same time.

Example:

GRANT SELECT,INSERT ON *.* TO 'zking'@'localhost' IDENTIFIED BY '1234' WITH GRANT OPTION;

4. Take back user rights

Delete some specific permissions of the user, the syntax is as follows:

REVOKE priv_type [(column_list)]...
ON database.table
FROM user [, user]...

The parameters in the REVOKE statement have the same meaning as the parameters in the GRANT statement. in:

  • The priv_type parameter indicates the type of permission;

  • The column_list parameter indicates which columns the permission acts on, and if there is no such parameter, it acts on the entire table;

  • The user parameter consists of a username and a hostname in the format "username'@'hostname'".

Example 1: Revoke some permissions from a user

REVOKE INSERT ON *.* FROM 'zking'@'localhost'

Example 2: Revoke all permissions from a user

REVOKE ALL PRIVILEGES, GRANT OPTION FROM 'zking'@'localhost'

5. View user permissions

Use the SHOW GRANTS FOR statement to view permissions. Its syntax format is as follows:

SHOW GRANTS FOR 'username'@'hostname';

Among them, username represents the user name, and hostname represents the host name or host IP.

Example:

SHOW GRANTS FOR 'xw'@'localhost';

6. Delete user

Use the DROP USER statement to view permissions. Its syntax format is as follows: 

DROP USER 'username'@'host';

where 'username' is the username of the user to delete, and 'host' is the host specifying the user.

For example, to delete a user named "john" and its associated permissions, execute the following command:

DROP USER 'john'@'localhost';

Reminder: Different versions may have different sentences. All the sentences in this article are based on MySQL8.0! !

That's all for this sharing, if you find it helpful, please give a blogger a thumbs up! !

Guess you like

Origin blog.csdn.net/weixin_74318097/article/details/131548130