当前位置:网站首页>Installation and use of MySQL under MySQL 19 Linux
Installation and use of MySQL under MySQL 19 Linux
2022-07-06 10:43:00 【Protect our party a Yao】
One . Instructions before installation
1.1. Linux Preparation of systems and tools
- Install and start two virtual machines : CentOS 7.
- Installed with Xshell and Xftp Wait for a visit CentOS System tools .
- CentOS6 and CentOS7 stay MySQL Differences in the use of
1. A firewall :6 yes iptables,7 yes firewalld
2. The command to start the service :6 yes service,7 yes systemctl
1.2. Check to see if MySQL
- If you use rpm install , Check the RPM PACKAGE:
rpm -qa | grep -i mysql # -i Ignore case
- Check mysql service:
systemctl status mysqld.service
- If there is mysql-libs Old version of package , It is shown as follows :
- If it doesn't exist mysql-lib Version of , It is shown as follows :
1.3. MySQL The uninstall
- close mysql service
systemctl stop mysqld.service;
- View the current mysql Installation status
rpm -qa | grep -i mysql;
perhaps
yum list installed | grep mysql;
- Uninstall the installed programs found by the above command
yum remove mysql-xxx mysql-xxx mysql-xxx mysqk-xxxx
Be sure to unload clean , Repeat rpm -qa | grep -i mysql Confirm whether there are unloading residues .
- Delete mysql Related documents
Find related files
find / -name mysql
Delete the relevant files found by the above command
rm -rf xxx;
- Delete my.cnf
rm -rf /etc/my.cnf
Two . MySQL Of Linux Version installation
2.1. MySQL Of 4 The big version
- MySQL Community Server Community version , Free open source , Free download , But no official technical support , Suitable for most ordinary users .
- MySQL Enterprise Edition Enterprise version , Pay for , Can't download online , You can try 30 God . It provides more functions and more complete technical support , It is more suitable for enterprise customers with high requirements for database function and reliability .
- MySQL Cluster Cluster version , Free open source . It is used to set up cluster servers , You can put a few MySQL Server Encapsulate into a Server. It needs to be used on the basis of community version or enterprise version .
- MySQL Cluster CGE Advanced clustering , Pay for .
Besides , Officials also provide MySQL Workbench (GUITOOL) One for MySQL The design of the ER/ Database modeling tools . It is a famous database design tool DBDesigner4 Successor .MySQLWorkbench It's divided into two versions , Namely Community Edition (MySQL Workbench OSS)、 Commercial version (MySQL WorkbenchSE).
2.2. download MySQL Specify the version
- Download address
Official website : https://www.mysql.com - Open the website , Click on DOWNLOADS
then , Click on MySQL Community(GPL) Downloads - Click on MySQL Community Server
- stay General Availability(GA) Releases Select the appropriate version
If installed Windows Under the system MySQL , Recommended download MSI Erection sequence ; Click on Go to Download Page Download it
Windows Under the MySQL There are two installers installed
mysql-installer-web-community-8.0.25.0.msi Download program size :2.4M; Networking installation components are required during installation .
mysql-installer-community-8.0.25.0.msi Download program size :435.7M; You can install offline during installation . recommend . - Linux Installation under system MySQL In several ways :
5.1. Linux There are three common ways to install software under the system :
The way 1:rpm command
Use rpm The command installation extension is ".rpm" Software package .
.rpm The general format of the package :
The way 2:yum command
Networking required , from Internet access Of yum Source , Use it directly yum Command to install .
The way 3: Compile and install source code package
in the light of tar.gz This compression format , Use tar Command to unzip ; If it's any other compression format , Just use other commands .
5.2. Linux Installation under system MySQL, The official gives a variety of installation methods
Installation mode | characteristic |
---|---|
rpm | Simple installation , Poor flexibility , Unable to flexibly select the version 、 upgrade |
rpm repository | The installation package is very small , Version installation is simple and flexible , Easy upgrade , It needs to be installed online |
General binary package | Installation is more complicated , High flexibility , The platform has good universality |
Source package | Installation is the most complicated , Long time , The parameter setting is flexible , Good performance |
You can't directly choose CentOS 7 The version of the system , So choose the corresponding Red Hat Enterprise Linux
https://downloads.mysql.com/archives/community/ Direct point Download download RPM Bundle Full package . Includes all the following components . You don't need to download one by one .
- Download the tar package , Open it with a compressor
After decompressing rpm Installation package ( The red box is the extracted installation package )
2.3. CentOS7 Lower inspection MySQL rely on
- Check /tmp Temporary directory permissions ( essential )
because mysql During installation , Will pass mysql The user is in /tmp New under the directory tmp_db file , So please give /tmp Greater authority . perform :
chmod -R 777 /tmp
- Before the installation , Checking depends on
rpm -qa|grep libaio
If there is net-tools The package is as follows :
rpm -qa|grep net-tools
If there is no need to go to centos In the installation disk rpm install . install linux If there is a graphical interface , These are all installed .
2.4. CentOS7 Next MySQL setup script
Copy the installer to /opt Under the table of contents
stay mysql The installation file directory of :( It must be carried out in order )
rpm -ivh mysql-community-common-8.0.26-1.el7.x86_64.rpm
rpm -ivh mysql-community-client-plugins-8.0.26-1.el7.x86_64.rpm
rpm -ivh mysql-community-libs-8.0.26-1.el7.x86_64.rpm
rpm -ivh mysql-community-client-8.0.26-1.el7.x86_64.rpm
rpm -ivh mysql-community-server-8.0.26-1.el7.x86_64.rpm
notes :
- When executed rpm -ivh mysql-community-libs-8.0.26-1.el7.x86_64.rpm There is an error : Dependency detection failed :mariadb-libs By mysql-community-libs-8.0.26-1.el7.x86_64 When replacing errors , perform :
yum remove mysql-libs
- When executed rpm -ivh mysql-community-server-8.0.26-1.el7.x86_64.rpm appear :
error : Dependency detection failed :
/usr/bin/perl By mysql-community-server-8.0.26-1.el7.x86_64 need
net-tools By mysql-community-server-8.0.26-1.el7.x86_64 need
perl(Getopt::Long) By mysql-community-server-8.0.26-1.el7.x86_64 need
perl(strict) By mysql-community-server-8.0.26-1.el7.x86_64 need
perform :
yum install net-tools
yum install -y perl-Module-Install.noarch
Then install :
rpm -ivh mysql-community-server-8.0.26-1.el7.x86_64.rpm
- . Be careful : For example, when checking the work , No inspection mysql Environment dependent installation mysql-community-server Will report a mistake .
- pm yes Redhat Package Manage abbreviation , adopt RPM Management of , Users can wrap the source code as rpm Is the file form of the extension , Easy to install .
- -i , --install Install package .
- -v , --verbose Provide more detailed information output .
- -h , --hash The hash mark is listed when the package is installed ( and -v The effect is better when used together ), Show the progress bar .
2.5. see MySQL edition
Execute the following command , If successful, it means that the installation is mysql success . similar java -version If you print the version and other information .
mysql --version
# or
mysqladmin --version
Execute the following command , Check whether the installation is successful . Need to increase the -i Don't be case sensitive , Otherwise we can't find .
rpm -qa|grep -i mysql
2.6. Initialization of services
In order to ensure that the owner of database directories and files is mysql The logged in user , If you are root Identity running mysql service , You need to perform the following command initialization :
mysqld --initialize --user=mysql
bright : --initialize Options default to “ Security ” Mode to initialize , Will be root The user generates a password and will The password is marked as expired , After logging in, you need to set a new password . Generated Temporary password Will record a copy in the log .
Check the password :
cat /var/log/mysqld.log
[email protected]: Followed by the initialization password
2.7. start-up MySQL, Check the status
# Add do not add .service Suffixes are OK
start-up :systemctl start mysqld.service
close :systemctl stop mysqld.service
restart :systemctl restart mysqld.service
Check the status :systemctl status mysqld.service
mysqld This executable represents MySQL Server program , Running this executable file can directly start a
Server process .
Check the process :
2.8. see MySQL Whether the service starts automatically
systemctl list-unit-files | grep mysqld.service
The default is enabled.
- If not enabled You can run the following command to set the auto start
systemctl enable mysqld.service
- If you want to avoid self starting , Run the following command
systemctl disable mysqld.service
3、 ... and . MySQL Sign in
3.1. For the first time login
adopt mysql -hlocalhost -P3306 -uroot -p Log in , stay Enter password: Enter the initialization password
3.2. Change Password
- Because the initialization password expires by default , So checking the database will report an error .
- Change Password :
alter user 'root'@'localhost' identified by '123456';
- 5.7 After the version ( Not included 5.7),mysql Added a new password security mechanism . Setting a new password is too simple and will report an error .
3.3. Set up remote login
3.3.1. The current problem
In use SQLyog or Navicat Configure remote connections in Mysql The following error messages are encountered when the database , This is because Mysql Configured... Caused by unsupported remote connection .
3.3.2. Confirm the network
Use... On remote machines ping ip Address Make sure the network is smooth .
Use... On remote machines telnet command Ensure that the port number is open visit .
expand : telnet Command on
3.3.3. Turn off the firewall or open ports
Mode one : Turn off firewall
CentOS6 :
service iptables stop
CentOS7:
systemctl start firewalld.service
systemctl status firewalld.service
systemctl stop firewalld.service
# Set boot to enable firewall
systemctl enable firewalld.service
# Set boot disable firewall
systemctl disable firewalld.service
Mode two : Open ports
- Check the open port number
firewall-cmd --list-all
- Set the open port number
firewall-cmd --add-service=http --permanent
firewall-cmd --add-port=3306/tcp --permanent
- service iptables restart
firewall-cmd --reload
3.4. Linux Modify the configuration under
stay Linux System MySQL Next test :
use mysql;
select Host,User from user;
You can see root The current host configuration information of the user is localhost.
modify Host For wildcard %
ost Column specifies the IP, such as user=root Host=192.168.1.1. This means that root Users can only pass through 192.168.1.1 Client access . user=root Host=localhost, It means that it can only be accessed through the local client . and % It's a wildcard , If Host=192.168.1.%, So that means as long as it's IP Address prefix is “192.168.1.” All clients of can connect . If Host=% , Express all IP All have connection permission .
Be careful : In a production environment, you can't save host Set to %, There will be security problems , Specific settings can be set according to the production environment IP Set it up .
update user set host = '%' where user ='root';
Host Set up “%” Then you can allow remote access .
Host Remember to execute after modification flush privileges Make the configuration take effect immediately :
flush privileges;
3.5. test
- If it is MySQL5.7 edition , You can use SQLyog perhaps Navicat Successfully connected to MySQL 了 .
- If it is MySQL8 edition , The following problems also occur when connecting :
Configuration new connection error : Wrong number 2058, The analysis is mysql Password encryption has changed .
resolvent :Linux Next mysql -u root -p Log in to your mysql database , then Implement this SQL:
ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY '123456';
And then reconfigure SQLyog The connection of , The connection is successful ,OK.
Four . MySQL8 Password strength evaluation ( understand )
4.1. MySQL Set passwords for different versions ( May appear )
- MySQL5.7 in : success
mysql> alter user 'root' identified by 'abcd1234';
Query OK, 0 rows affected (0.00 sec)
- MySQL8.0 in : Failure
mysql> alter user 'root' identified by 'abcd1234';
ERROR 1819 (HY000): Your password does not satisfy the current policy requirements
4.2. MySQL8 Previous security policy
stay MySQL 8.0 Before ,MySQL It uses validate_password Plug in detection 、 Verify account and password strength , Guarantee the security of the account .
- install / Enable plug-in mode 1: In the parameter file my.cnf Add parameters in .
[mysqld]
plugin-load-add=validate_password.so
\#ON/OFF/FORCE/FORCE_PLUS_PERMANENT: Whether to use the plug-in ( And mandatory / Permanent mandatory use )
validate-password=FORCE_PLUS_PERMANENT
explain 1: plugin library Medium validate_password The suffix of the file name varies according to the platform . about Unix and
Unix-like In terms of system , Its file suffix is .so, about Windows In terms of system , Its file suffix is .dll.
explain 2: After modifying the parameters, you must restart MySQL Service to take effect .
explain 3: Parameters FORCE_PLUS_PERMANENT To prevent the plug-in from MySQL It is unloaded at runtime . When you uninstall the plug-in, you will report an error . As shown below .
mysql> SELECT PLUGIN_NAME, PLUGIN_LIBRARY, PLUGIN_STATUS, LOAD_OPTION
-> FROM INFORMATION_SCHEMA.PLUGINS
-> WHERE PLUGIN_NAME = 'validate_password';
mysql> UNINSTALL PLUGIN validate_password;
ERROR 1702 (HY000): Plugin 'validate_password' is force_plus_permanent and can not be
unloaded
mysql>
- install / Enable plug-in mode 2: Run time command installation ( recommend )
INSTALL PLUGIN validate_password SONAME 'validate_password.so';
perhaps
INSTALL COMPONENT 'file://component_validate_password';
The metadata will also be registered to this method , That is to say mysql.plugin In the table , So don't worry MySQL After restart, the plug-in will fail .
4.3. MySQL8 Security policy
4.3.1. validate_password explain
MySQL 8.0, The introduction of server components (Components) This feature ,validate_password The plug-in has been re implemented with server components
present .8.0.25 Version of the database , Auto install by default validate_password Components .
Before installing the plug-in , Execute the following two instructions , Execution effect :
show variables like 'validate_password%';
SELECT * FROM mysql.component;
After installing the plug-in , Execute the following two instructions , Execution effect :
About validate_password Description of system variables corresponding to components :
Options | The default value is | Parameters to describe |
---|---|---|
validate_password_check_user_name | ON | Set to ON The password can be set to the current user name . |
validate_password_dictionary_file | The pathname of the dictionary file used to check the password , The default is empty. | |
validate_password_length | 8 | Minimum password length , In other words, the password length must be greater than or equal to 8 |
validate_password_mixed_case_count | 1 | If the password policy is medium or stronger ,validate_password Minimum number of lowercase and uppercase characters required for passwords . For a given value, the password must have so many lowercase characters and so many uppercase characters . |
validate_password_number_count | 1 | The number of digits the password must contain |
validate_password_policy | MEDIUM | Password strength level , You can use numerical values 0、1、2 Or the corresponding symbolic value LOW、MEDIUM、STRONG To specify the . 0/LOW : Check length only .1/MEDIUM : Check the length 、 Numbers 、 Case write 、 Special characters . 2/STRONG : Check the length 、 Numbers 、 Case write 、 Special characters 、 Dictionary file . |
validate_password_special_char_count | 1 | The number of special characters a password must contain |
Tips :
The default values of components and plug-ins may be different . for example ,MySQL5.7.validate_password_check_user_name The default value is OFF.
4.3.2. Modify security policy
Modify password verification security strength
SET GLOBAL validate_password_policy=LOW;
SET GLOBAL validate_password_policy=MEDIUM;
SET GLOBAL validate_password_policy=STRONG;
SET GLOBAL validate_password_policy=0; # For LOW
SET GLOBAL validate_password_policy=1; # For MEDIUM
SET GLOBAL validate_password_policy=2; # For HIGH
# Be careful , If it's a plug-in ,SQL by set global validate_password_policy=LOW
Besides , You can also change the length of characters in the password
set global validate_password_length=1;
4.3.3. Password strength test
If you create a password, you encounter “Your password does not satisfy the current policy requirements”, The function component can be used to detect whether the password meets the conditions : 0-100. When the assessment is in 100 It means that the most basic rules are used : Capitalization + A lowercase letter + Special characters + It's made up of numbers 8 Password above .
SELECT VALIDATE_PASSWORD_STRENGTH('medium');
SELECT VALIDATE_PASSWORD_STRENGTH('K354*45jKd5');
Be careful : If not installed validate_password Components or plug-ins , Then this function always returns 0. On the password complexity strategy corresponding to password complexity . As shown in the table below :
Password Test | Return Value |
---|---|
Length < 4 | 0 |
Length ≥ 4 and < validate_password.length | 25 |
Satisfies policy 1 (LOW) | 50 |
Satisfies policy 2 (MEDIUM) | 75 |
Satisfies policy 3 (STRONG) | 100 |
4.4. Uninstall plugins 、 Components ( understand )
Uninstall plugins
UNINSTALL PLUGIN validate_password;
Uninstall components
UNINSTALL COMPONENT 'file://component_validate_password';
5、 ... and . Related operations of character set
5.1. modify MySQL5.7 Character set
5.1.2. Modification steps
stay MySQL 8.0 Before the release , The default character set is latin1 ,utf8 The character set points to utf8mb3 . Website developers often change the code to utf8 Character set . If you forget to change the default code , There will be a problem of garbled code . from MySQL8.0 Start , The default encoding of the database will be changed to utf8mb4 , So as to avoid the above problem of garbled code .
operation 1: View the default character set
show variables like 'character%';
# perhaps
show variables like '%char%'
MySQL8.0 In the implementation of :
MySQL5.7 In the implementation of :
MySQL 5.7 The default client and server use latin1 , No Chinese support , Saving Chinese will report an error .MySQL5.7 The screenshot is as follows :
stay MySQL5.7 When adding Chinese data to , Report errors :
create database dbtest1;
create table emp1(id int,lname varchar(15));
show tables;
insert into emp1 values (1,' Zhang San ');
Because by default , The table is created using latin1 . as follows :
show create table emp1;
operation 2: Modify character set
vim /etc/my.cnf
stay MySQL5.7 Or in previous versions , Add Chinese character set configuration at the end of the file :
character_set_server=utf8
operation 3: Restart MySQL service
systemctl restart mysqld
notes : But the original library 、 The setting of the original table will not change , Parameter modification is only effective for the newly created database .
5.1.2. Existing library & Table character set changes
MySQL5.7 In the version , Previously created Libraries , The character set of the created table is still latin1.
Modify the character set of the created database
alter database dbtest1 character set 'utf8';
Modify the character set of the created data table
alter table emp1 convert to character set 'utf8';
Add data
insert into emp1 values(2,' Zhang San ');
Be careful : But if the original data is not used ’utf8’ Code words , The encoding of the data itself will not change . Existing data needs to be exported or deleted , And then re insert .
5.2. Character sets at all levels
MySQL Yes 4 Two levels of character sets and comparison rules , Namely :
1. Server level
2. Database level
3. Table level
4. Column level
The implementation is as follows SQL sentence :
show variables like 'character%';
- character_set_server: Server level character set .
- character_set_database: The character set of the current database .
- character_set_client: The character set used by the server to decode the request .
- character_set_connection: When the server processes the request, it will change the request string from character_set_client To character_set_connection.
- character_set_results: The character set used by the server to return data to the client .
5.2.1. Server level
character_set_server : Server level character set .
We can use the startup option when starting the server program or when the server program is running SET Statement to modify the values of these two variables . For example, we can write this in the configuration file :
[server]
character_set_server=gbk # Default character set
collation_server=gbk_chinese_ci # The corresponding default comparison rule
After reading the configuration file when the server starts, the values of these two system variables are modified .
5.2.2. Database level
character_set_database : The character set of the current database .
When we create and modify a database, we can specify the character set and comparison rules of the database , The specific syntax is as follows :
CREATE DATABASE Database name
[[DEFAULT] CHARACTER SET Character set name ]
[[DEFAULT] COLLATE Comparison rule name ];
ALTER DATABASE Database name
[[DEFAULT] CHARACTER SET Character set name ]
[[DEFAULT] COLLATE Comparison rule name ];
5.2.3. Table level
We can also specify the character set and comparison rules of the table when creating and modifying the table , The grammar is as follows :
CREATE TABLE Table name ( Column information )
[[DEFAULT] CHARACTER SET Character set name ]
[COLLATE Comparison rule name ]]
ALTER TABLE Table name
[[DEFAULT] CHARACTER SET Character set name ]
[COLLATE Comparison rule name ]
If the statement creating and modifying the table does not specify the character set and comparison rules , The character set and comparison rule of the database where the table is located will be used as the character set and comparison rule of the table .
5.2.4. Column level
For columns that store strings , Different columns in the same table can have different character sets and comparison rules . When we create and modify a column definition, we can specify the character set and comparison rules of the column , The grammar is as follows :
CREATE TABLE Table name (
Name String type [CHARACTER SET Character set name ] [COLLATE Comparison rule name ],
Other columns ...
);
ALTER TABLE Table name MODIFY Name String type [CHARACTER SET Character set name ] [COLLATE Comparison rule name ];
For a column , If the character set and comparison rules are not specified in the created and modified statements , The column of the table will be used
And comparison rule as the character set and comparison rule of the column .
Tips :
When converting the character set of a column, you need to pay attention to , If the data stored in the front of conversion cannot be represented by the converted character set, an error will occur . For example, the character set used by the original column is utf8, Some Chinese characters are stored in the column , Now convert the character set of the column to ascii That would make a mistake , because ascii The character set cannot represent Chinese characters .
5.2.5. Summary
We introduce this 4 The relationship between level character sets and comparison rules is as follows :
- If Create or modify Columns There are no explicit character sets and comparison rules specified when , Then this column The default table is Character sets and comparison rules .
- If Create table time There are no explicit character sets and comparison rules , Then the table By default, the database is used Character sets and comparison rules .
- If When creating a database There are no explicit character sets and comparison rules , Then the database By default, the server's name is used Character sets and comparison rules .
Knowing these rules , For a given table , We should know the character set and comparison rules of its columns , Thus, the storage space occupied by the actual data of each column is determined according to the type of this column .
For example, columns col The character set used is gbk , A character ‘ I ’ stay gbk The code in is 0xCED2 , Takes two bytes , The actual data of two characters takes up 4 Bytes . If you change the character set of this column to utf8 Words , These two characters actually occupy 6 Bytes .
5.3. Character sets and comparison rules ( understand )
5.3.1. utf8 And utf8mb4
utf8 The character set indicates that a character needs to use 1~4 Bytes , But some of the characters we often use 1~3 It's just a byte . The character set represents the maximum byte length of a character , In some aspects, it will affect the storage and performance of the system , So design MySQL The designer secretly defined two concepts :
- utf8mb3 : Castrated utf8 Character set , Use only 1~3 Bytes represent characters .
- utf8mb4 : authentic utf8 Character set , Use 1~4 Bytes represent characters .
5.3.2. Compare the rules
The above table ,MySQL The version supports 41 A character set , Among them Default collation Columns represent a default comparison rule in this character set , It contains the language in which the comparison rule mainly works , such as utf8_polish_ci It means to compare the rules in Polish , utf8_spanish_ci It's a comparison of Spanish rules , utf8_general_ci It's a general rule of comparison .
The suffix indicates whether the comparison rule distinguishes accents in the language 、 Case write . As follows :
suffix | English interpretation | describe |
---|---|---|
_ai | accent insensitive | Stress insensitive |
_as | accent sensitive | Distinguish between stress |
_ci | case insensitive | Case insensitive |
_cs | case sensitive | Case sensitive |
_bin | binary | Compare in binary terms |
The last column Maxlen , It represents this kind of character set, indicating that a character needs up to a few bytes .
Common operations 1:
# see GBK Comparison rules for character sets
SHOW COLLATION LIKE '%gbk%';
# see UTF-8 Comparison rules for character sets
SHOW COLLATION LIKE '%utf8%';
Common operations 2:
# View the character set and comparison rules of the server
SHOW VARIABLES LIKE '%_server';
# View the character set and comparison rules of the database
SHOW VARIABLES LIKE '%_database';
# View the character set of the specific database
SHOW CREATE DATABASE dbtest1;
# Modify the character set of the specific database
ALTER DATABASE dbtest1 DEFAULT CHARACTER SET 'utf8' COLLATE 'utf8_general_ci';
Common operations 3:
# View the character set of the table
show create database dbtest1;
# View table comparison rules
show create table emp1;
# Modify the character set and comparison rules of the table
ALTER TABLE emp1 DEFAULT CHARACTER SET 'utf8' COLLATE 'utf8_general_ci';
5.4. The change of character set from request to response
System variables | describe |
---|---|
character_set_client | The character set used by the server to decode the request |
character_set_connection | When the server processes the request, it will change the request string from character_set_client To character_set_connection |
character_set_results | The character set used by the server to return data to the client |
The default values of these system variables on my computer are as follows ( The default values may vary from operating system to operating system ):
show variables like '%character%';
In order to reflect the changes of character set in the process of request processing , Here, the value of a system variable is specially modified :
set character_set_connection = gbk;
Now suppose that the request sent by our client is the following string :
SELECT * FROM t WHERE s = ' I ';
In order to facilitate everyone to understand this process , We only analyze characters ‘ I ’ In this process, the character set is converted .
Now let's look at the changes in the character set from the request sent to the result returned :
- The character set used by the client to send the request
Generally, the character set used by the client is consistent with the current operating system , Different operating systems may use different character sets , as follows :
- class Unix The system uses utf8.
- Windows It uses gbk.
When the client uses utf8 Character set , character ‘ I ’ The byte form in the request sent to the server is :0xE68891
Tips
If you're using visualization tools , such as navicat And so on. , These tools may use custom character sets
To encode the string sent to the server , Instead of using the default character set of the operating system
( So when learning, try to use the command line window ).
- The request received by the server from the client is actually a string of binary bytes , It will think that the character set used by this string of bytes is character_set_client , Then convert this string of bytes into character_set_connection Character set encoded character .
Because on my computer character_set_client The value of is utf8 , First of all, according to utf8 Character set pair byte string 0xE68891 decode , The resulting string is ‘ I ’ , And then according to character_set_connection Represents the character set , That is to say gbk Encoding , The result is a byte string 0xCED2 . - Because of the watch t The column of col It's using gbk Character set , And character_set_connection Agreement , So go directly to the column and find the byte value is 0xCED2 The record of , Finally found a record .
Tips
If a column uses a character set and character_set_connection If the character set represented is inconsistent , It needs to be done
A character set conversion .
- In the record found in the previous step col Column is actually a byte string 0xCED2 , col The column is gbk Coded , So first we will use this byte string gbk decode , Get a string ‘ I ’ , Then use this string character_set_results Represents the character set , That is to say utf8 Encoding , Got a new byte string :0xE68891 , Then send it to the client .
- Because the character set used by the client is utf8 , So you can successfully 0xE68891 Interpret as character I , So that it can be displayed on our display , So we humans also understand the returned results .
The summary diagram is as follows :
6、 ... and . SQL Case specification
6.1. Windows and Linux Platform differences
stay SQL in , Keywords and function names are case insensitive , such as SELECT、WHERE、ORDER、GROUP BY Other key words , as well as ABS、MOD、ROUND、MAX Equal function name .
But in the SQL in , You still have to determine the case specification , Because in Linux and Windows In the environment , You may encounter different case problems . windows System default case insensitive , however linux The system is case sensitive .
Check it with the following command :
- Windows Under the system :
SHOW VARIABLES LIKE '%lower_case_table_names%;
- Linux Under the system :
- lower_case_table_names Parameter value setting :
- The default is 0, Case sensitive .
- Set up 1, Case insensitive . Create a table , All databases are stored on disk in lowercase form , about sql Statements are converted to lowercase to find tables and databases .
- Set up 2, The created tables and databases are stored according to the statement format , All searches are made in lowercase .
- On two platforms SQL The difference between case and case, specifically :
MySQL stay Linux Next database name 、 Table name 、 Name 、 This is the case rule for aliases :
1、 Database name 、 Table name 、 The table alias 、 Variable names are strictly case sensitive ;
2、 keyword 、 The function name is in SQL Case insensitive in ;
3、 Name ( Or field name ) Alias with column ( Or field alias ) In all cases, case is ignored ;
notes :MySQL stay Windows All cases are not case sensitive
6.2. Linux Set the case rule
When you want to make it case insensitive , To be in my.cnf This configuration file [mysqld] Add lower_case_table_names=1 , Then restart the server .
notes :
- However, you need to convert the original database and tables to lowercase before restarting the database instance , Otherwise, the database name will not be found .
- This parameter applies to MySQL5.7. stay MySQL 8 It is forbidden to restart MySQL Service will lower_case_table_names Set to be different from initialization MySQL Service settings lower_case_table_names value . If you have to MySQL8 Set to case insensitive , The specific steps are: :
1、 stop it MySQL service
2、 Delete data directory , Delete immediately /var/lib/mysql Catalog
3、 stay MySQL The configuration file ( /etc/my.cnf ) Add lower_case_table_names=1
4、 start-up MySQL service
6.3. SQL Write suggestions
If your variable name naming convention is not uniform , There may be errors . Here's a suggestion for naming conventions :
1. Keywords and function names are all capitalized ;
2. Database name 、 Table name 、 Table alias 、 Field name 、 All fields, aliases, etc. are lowercase ;
3. SQL The statement must end with a semicolon .
Database name 、 Table name and field name are in Linux MySQL The environment is case sensitive , Therefore, it is recommended that you unify the naming rules of these fields , For example, all in lowercase .
Although keywords and function names are in SQL Case insensitive in , That is, if it is lowercase, it can also execute . But at the same time, all keywords and function names are capitalized , In order to distinguish the database name 、 Table name 、 Field name .
7、 ... and . sql_mode Reasonable setting of
7.1. Loose mode vs Strict mode
- Loose mode :
If the setting is loose mode , So when we insert data , Even if it's given the wrong data , It may also be accepted , And don't report mistakes .
give an example : When I create a table , One of the fields in this table is name, to name When setting the field type of char(10) , If I
When inserting data , among name This field corresponds to a piece of data It's longer than 10 , for example ’1234567890abc’, Exceeds the set field length 10, Then there will be no mistake , And take the front 10 Save characters , That is to say, your data is stored as ’1234567890’, and ’abc’ There is no the . however , The data we gave is wrong , Because the field length is exceeded , But there was no mistake , also mysql Disposed of and accepted , This is the effect of the relaxed model .
Application scenarios : By setting sql mode For the relaxed mode , To ensure that most sql Conforming to the standard sql grammar , In this way, the application is carried out between different databases transfer when , There is no need for business sql Make big changes . - Strict mode :
The above loose mode error appears , It's right to report a mistake , therefore MySQL5.7 The version will sql_mode Default to strict mode . So in Production environment in , What we have to adopt is a strict model , , in turn, Development 、 Test environment Your database must also be set , In this way, problems can be found during the development and testing phase . And even if we use MySQL5.6, It should also be changed to a strict model .
Development experience :MySQL The database always wants to take care of all the operations related to data , Including data verification , Actually development
in , We should be in ourselves The developed project program level makes these checks , Although there are some steps in writing the project , But after that , We are doing database migration or project migration , It will be much more convenient .
The possible problems after changing to strict mode :
If the setup mode includes NO_ZERO_DATE , that MySQL Database is not allowed to insert zero date , Inserting a zero date throws an error instead of a warning . for example , Table with fields TIMESTAMP Column ( If it is not declared NULL Or display DEFAULT Clause ) Will automatically assign DEFAULT ‘0000-00-00 00:00:00’( Zero time stamp ), This is obviously not satisfied sql_mode Medium NO_ZERO_DATE And report wrong .
7.2. Mode viewing and setting
- View the current sql_mode
select @@session.sql_mode
select @@global.sql_mode
# perhaps
show variables like 'sql_mode';
- Temporary setting mode : Set the settings in the current window sql_mode:
SET GLOBAL sql_mode = 'modes...'; # overall situation
SET SESSION sql_mode = 'modes...'; # Current session
give an example :
# Change to strict mode . This method only works in the current session , Closing the current session will not take effect .
set SESSION sql_mode='STRICT_TRANS_TABLES';
# Change to strict mode . This method works in the current service , restart MySQL Failure after service .
set GLOBAL sql_mode='STRICT_TRANS_TABLES';
- Permanent setting mode : stay /etc/my.cnf Middle configuration sql_mode
stay my.cnf file (windows System is my.ini file ), newly added :
[mysqld]
sql_mode=ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR
_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION
then restart MySQL .
Of course, restart is forbidden in the production environment MySQL Service , So using Temporary setting mode + Permanent setting mode To solve online problems , So even if it's restarted one day MySQL service , It's going to be permanent .
边栏推荐
- MySQL25-索引的创建与设计原则
- Not registered via @enableconfigurationproperties, marked (@configurationproperties use)
- pytorch的Dataset的使用
- Pytorch LSTM实现流程(可视化版本)
- February 13, 2022 - Maximum subarray and
- Copy constructor template and copy assignment operator template
- ++Implementation of I and i++
- Time complexity (see which sentence is executed the most times)
- Case identification based on pytoch pulmonary infection (using RESNET network structure)
- Ueeditor internationalization configuration, supporting Chinese and English switching
猜你喜欢
Mysql35 master slave replication
Use JUnit unit test & transaction usage
用于实时端到端文本识别的自适应Bezier曲线网络
CSDN question and answer module Title Recommendation task (I) -- Construction of basic framework
Pytoch LSTM implementation process (visual version)
Moteur de stockage mysql23
What is the current situation of the game industry in the Internet world?
Typescript入门教程(B站黑马程序员)
CSDN问答模块标题推荐任务(一) —— 基本框架的搭建
MySQL35-主从复制
随机推荐
实现以form-data参数发送post请求
MySQL25-索引的创建与设计原则
MySQL19-Linux下MySQL的安装与使用
pytorch的Dataset的使用
Solution to the problem of cross domain inaccessibility of Chrome browser
MySQL combat optimization expert 12 what does the memory data structure buffer pool look like?
Not registered via @enableconfigurationproperties, marked (@configurationproperties use)
Anaconda3 installation CV2
Mysql24 index data structure
Not registered via @EnableConfigurationProperties, marked(@ConfigurationProperties的使用)
基于Pytorch的LSTM实战160万条评论情感分类
Global and Chinese market of thermal mixers 2022-2028: Research Report on technology, participants, trends, market size and share
[C language] deeply analyze the underlying principle of data storage
MySQL24-索引的数据结构
Global and Chinese market of wafer processing robots 2022-2028: Research Report on technology, participants, trends, market size and share
Mysql33 multi version concurrency control
[after reading the series] how to realize app automation without programming (automatically start Kwai APP)
[Li Kou 387] the first unique character in the string
Solve the problem of remote connection to MySQL under Linux in Windows
Mysql21 - gestion des utilisateurs et des droits