当前位置:网站首页>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

  1. Install and start two virtual machines : CentOS 7.
  2. Installed with Xshell and Xftp Wait for a visit CentOS System tools .
  3. 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

  1. If you use rpm install , Check the RPM PACKAGE:
rpm -qa | grep -i mysql # -i  Ignore case 
  1. Check mysql service:
systemctl status mysqld.service
  1. If there is mysql-libs Old version of package , It is shown as follows :
     Insert picture description here
  2. If it doesn't exist mysql-lib Version of , It is shown as follows :
     Insert picture description here

1.3. MySQL The uninstall

  1. close mysql service
systemctl stop mysqld.service;
  1. View the current mysql Installation status
rpm -qa | grep -i mysql;
 perhaps 
yum list installed | grep mysql;
  1. 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 .

  1. Delete mysql Related documents
    Find related files
find / -name mysql

Delete the relevant files found by the above command

rm -rf xxx;
  1. Delete my.cnf
rm -rf /etc/my.cnf

Two . MySQL Of Linux Version installation

2.1. MySQL Of 4 The big version

  1. MySQL Community Server Community version , Free open source , Free download , But no official technical support , Suitable for most ordinary users .
  2. 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 .
  3. 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 .
  4. 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

  1. Download address
    Official website : https://www.mysql.com
  2. Open the website , Click on DOWNLOADS
    then , Click on MySQL Community(GPL) Downloads
     Insert picture description here
  3. Click on MySQL Community Server
     Insert picture description here
  4. 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
     Insert picture description here
    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 .
  5. 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 :
     Insert picture description here
    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 .
 Insert picture description here

  1. Download the tar package , Open it with a compressor
     Insert picture description here
    After decompressing rpm Installation package ( The red box is the extracted installation package )

 Insert picture description here

2.3. CentOS7 Lower inspection MySQL rely on

  1. 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
  1. Before the installation , Checking depends on
rpm -qa|grep libaio

 Insert picture description here
If there is net-tools The package is as follows :

rpm -qa|grep net-tools

 Insert picture description here
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 :

  1. 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
  1. 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

 Insert picture description here 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

 Insert picture description here

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

 Insert picture description here [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 .

 Insert picture description here
Check the process :
 Insert picture description here

2.8. see MySQL Whether the service starts automatically

systemctl list-unit-files | grep mysqld.service

 Insert picture description here 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

 Insert picture description here

3.2. Change Password

  1. Because the initialization password expires by default , So checking the database will report an error .
  2. Change Password :
alter user 'root'@'localhost' identified by '123456';
  1. 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 .
 Insert picture description here

3.3.2. Confirm the network

  1. Use... On remote machines ping ip Address Make sure the network is smooth .

  2. Use... On remote machines telnet command Ensure that the port number is open visit .
     Insert picture description here  Insert picture description here

  3. expand : telnet Command on
     Insert picture description here

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

 Insert picture description here
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;

 Insert picture description here
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 .
 Insert picture description here 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 :
     Insert picture description here 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 )

  1. MySQL5.7 in : success
mysql> alter user 'root' identified by 'abcd1234';
Query OK, 0 rows affected (0.00 sec)
  1. 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 .

  1. 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';

 Insert picture description here

mysql> UNINSTALL PLUGIN validate_password;
ERROR 1702 (HY000): Plugin 'validate_password' is force_plus_permanent and can not be
unloaded
mysql>
  1. 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';

 Insert picture description here 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;

 Insert picture description here
After installing the plug-in , Execute the following two instructions , Execution effect :
 Insert picture description here
About validate_password Description of system variables corresponding to components :

Options The default value is Parameters to describe
validate_password_check_user_nameON 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_length8 Minimum password length , In other words, the password length must be greater than or equal to 8
validate_password_mixed_case_count1 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_count1 The number of digits the password must contain
validate_password_policyMEDIUM 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_count1 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');

 Insert picture description here

SELECT VALIDATE_PASSWORD_STRENGTH('K354*45jKd5');

 Insert picture description here
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 TestReturn Value
Length < 40
Length ≥ 4 and < validate_password.length25
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;

 Insert picture description here 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 :
 Insert picture description here MySQL5.7 In the implementation of :

 Insert picture description here
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;

 Insert picture description here

create table emp1(id int,lname varchar(15));
show tables;

 Insert picture description here

insert into emp1 values (1,' Zhang San ');

 Insert picture description here Because by default , The table is created using latin1 . as follows :

show create table emp1;

 Insert picture description here
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

 Insert picture description here
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.
 Insert picture description here
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 ');

 Insert picture description here
 Insert picture description here
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%';

 Insert picture description here

  1. character_set_server: Server level character set .
  2. character_set_database: The character set of the current database .
  3. character_set_client: The character set used by the server to decode the request .
  4. character_set_connection: When the server processes the request, it will change the request string from character_set_client To character_set_connection.
  5. 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 :

  1. 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 .
  2. 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 .
  3. 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 :

  1. utf8mb3 : Castrated utf8 Character set , Use only 1~3 Bytes represent characters .
  2. 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
_aiaccent insensitive Stress insensitive
_asaccent sensitive Distinguish between stress
_cicase insensitive Case insensitive
_cscase sensitive Case sensitive
_binbinary 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';

 Insert picture description here  Insert picture description here
 Insert picture description here
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%';

 Insert picture description here
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 :

  1. 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 ).
  1. 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 .
  2. 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 .
  1. 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 .
  2. 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 :
     Insert picture description here

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%;

 Insert picture description here

  • Linux Under the system :
     Insert picture description here
  • lower_case_table_names Parameter value setting :
  1. The default is 0, Case sensitive .
  2. 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 .
  3. 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 :

  1. 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 .
  2. 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

  1. 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 .
  2. 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';

 Insert picture description here  Insert picture description here

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

原网站

版权声明
本文为[Protect our party a Yao]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060911326337.html