当前位置:网站首页>Mysql36 database backup and recovery
Mysql36 database backup and recovery
2022-07-06 10:23:00 【Protect our party a Yao】
One . Physical backup and logical backup
The physical backup : Backup data files , Dump database physical files to a directory . Physical backup recovery is faster , But it takes up a lot of space ,MySQL Can be used in the xtrabackup Tools for physical backup .
Logical backup : Use tools to export database objects , Summary into backup file . Slow recovery of logical backup , But it takes up little space , More flexible .MySQL The common logical backup tool in is mysqldump . Logical backup is Backup sql sentence , Performing a backup at the time of recovery sql Statement to achieve the reproduction of database data .
Two . mysqldump Realize logical backup
2.1. Back up a database
Basic grammar :
mysqldump –u User name –h Host name –p password Name of the database to be backed up [tbname, [tbname...]]> Backup filename
call .sql
explain : The file name with suffix... Is not required .sql, For example, the suffix is .txt Your files are also OK .
give an example : Use root User backup zyy_master_slave database :
mysqldump -uroot -p zyy_master_slave>zyy_master_slave.sql
mysqldump -uroot -p zyy_master_slave > /var/lib/mysql/cptest/zyy_master_slave.sql
vim zyy_master_slave.sql
2.2. Back up all databases
If you want to use mysqldump Back up the entire instance , have access to --all-databases or -A Parameters :
mysqldump -uroot -pxxxxxx --all-databases > all_database.sql
mysqldump -uroot -pxxxxxx -A > all_database.sql
2.3. Backup part of the database
Use --databases or -B Parameters , This parameter is followed by the database name , Multiple databases are separated by spaces . If specified databases Parameters , There will be a statement to create the database in the backup file , If no parameters are specified , There is no . The grammar is as follows :
mysqldump –u user –h host –p --databases [ Database name 1 [ Database name 2...]] > Backup file name .sql
give an example :
mysqldump -uroot -p --databases zyy_master_slave dbtest3>two_database.sql
perhaps
mysqldump -uroot -p -B zyy_master_slave dbtest3 > two_database.sql
2.4. Back up some tables
such as , Make a backup before the table changes . The grammar is as follows :
mysqldump –u user –h host –p Database name [ Table name 1 [ Table name 2...]] > Backup file name .sql
give an example : Backup zyy_master_slave Database based student surface
mysqldump -uroot -p zyy_master_slave student> student.sql
student.sql The contents of the document are as follows
You can see ,student The file is similar to the backed up library file . The difference is ,student The file contains only book surface DROP、CREATE and INSERT sentence .
To back up multiple tables, use the following command , Such as backup mytbl and student surface :
# Back up multiple tables
mysqldump -uroot -p zyy_master_slave mytbl student> 2_tables_bak.sql
2.5. Backup some data of single table
Sometimes a table has a lot of data , We just need some data . It can be used at this time --where Options. .where The conditions to be met are attached .
give an example : Backup student In the table id Less than 10 The data of :
mysqldump -uroot -p zyy_master_slave student --where="id < 10 " > student_part_id10_low_bak.sql
2.6. Exclude backups of some tables
If we want to back up a library , But some tables have a large amount of data or are not related to the business , At this time, we can consider excluding these watches , alike , Options --ignore-table You can do this .
mysqldump -uroot -p zyy_master_slave --ignore-table=zyy_master_slave .student > no_stu_bak.sql
By specifying as follows, it is determined that there is no... In the file student Table structure :
grep "student" no_stu_bak.sql
2.7. Back up only the structure or only the data
Only the backup structure can be used --no-data Shorthand for -d Options ; Only backup data can be used --no-create-info Shorthand for -t Options
- Just back up the structure
mysqldump -uroot -p zyy_master_slave --no-data > no_data_bak.sql
# Use grep command , Can't find insert Related statements , Indicates that there is no data backup .
grep "INSERT" no_data_bak.sql
- Backup data only
mysqldump -uroot -p zyy_master_slave --no-create-info > atguigu_no_create_info_bak.sql
# Use grep command , Can't find create Related statements , Indicates that there is no data structure .
grep "CREATE" atguigu_no_create_info_bak.sql
2.8. The backup contains stored procedures 、 function 、 event
mysqldump Backup does not contain stored procedures by default , Custom functions and events . have access to --routines or -R Option to back up stored procedures and functions , Use --events or -E Parameters to back up events .
give an example : Back up the entire MYSQLTEST library , Contains stored procedures and events :
- Use the following SQL You can view which stored procedures or functions exist in the current library
SELECT SPECIFIC_NAME,ROUTINE_TYPE ,ROUTINE_SCHEMA FROM information_schema.Routines WHERE ROUTINE_SCHEMA="MYSQLTEST";
Now back up MYSQLTEST Database data , Functions and stored procedures .
mysqldump -uroot -p -R -E --databases MYSQLTEST> fun_MYSQLTEST_bak.sql
Query whether the function exists in the backup file , As shown below , You can see that it does contain functions .
2.9. mysqldump Common options
mysqldump Other common options are as follows :
- –add-drop-database: At every CREATE DATABASE Add before statement DROP DATABASE sentence .
- –add-drop-tables: At every CREATE TABLE Add before statement DROP TABLE sentence .
- –add-locking: use LOCK TABLES and UNLOCK TABLES Statement references each table dump . Insert faster when reloading dump files .
- –all-database, -A: Dump all tables in all databases . And use –database The options are the same , Name all databases on the command line .
- –comment[=0|1]: If set to 0, It is forbidden to dump other information in the file , For example, program version 、 Server version and host .–skip-comments And –comments=0 Same result for . The default value is 1, Include additional information .
- –compact: Produce a small amount of output . This option disables annotations and enables –skip-add-drop-tables、–no-set-names、–skip-disable-keys and –skip-add-locking Options .
- –compatible=name: Generated with other database systems or old MySQL Server more compatible output , The value can be ansi、MySQL323、MySQL40、postgresql、oracle、mssql、db2、maxdb、no_key_options、no_table_options perhaps no_field_options.
- –complete_insert, -c: Use the complete INSERT sentence .
- –debug[=debug_options], -#[debug_options]: Write debug log .
- –delete,-D: Empty table before importing text file .
- –default-character-set=charset: Use charsets Default character set . If not specified , Just use utf8.
- –delete–master-logs: On the primary replication server , Delete the binary log after the dump operation . This option is automatically enabled -master-data.
- –extended-insert,-e: Use includes several VALUES Multiple lines of the list INSERT grammar . This makes the dump file smaller , Reloading files can speed up insertion .
- –flush-logs,-F: Refresh before starting dump MySQL Server log files . This option requires RELOAD jurisdiction .
- –force,-f: During table dump , Even if SQL Mistakes continue .
- –lock-all-tables,-x: Lock all tables in all databases . In the overall dump process, it is realized by global locking . This option turns off automatically
- –single-transaction and –lock-tables.
- –lock-tables,-l: Lock all tables before starting dump . use READ LOCAL Lock the table to allow parallel inserts MyISAM surface . For the transaction table ( for example InnoDB and BDB),–single-transaction Is a better option , Because it doesn't need to lock the table at all .
- –no-create-db,-n: This option disables CREATE DATABASE /!32312 IF NOT EXIST/db_name sentence , If given –database or –all-database Options , It is included in the output .
- –no-create-info,-t: Export data only , Without adding CREATE TABLE sentence .
- –no-data,-d: Do not write any row information of the table , Only dump the structure of the table .
- –opt: This option is shorthand , It can dump quickly and produce a file that can be loaded quickly MySQL Dump file of the server . This option is on by default , But you can use –skip-opt Ban .
- –password[=password],-p[password]: The password used when connecting to the server .-port=port_num,-P port_num: jointed TCP/IP Port number .
- –protocol={TCP|SOCKET|PIPE|MEMORY}: Connection protocol used .
- –replace,-r –replace and –ignore: Controls the processing of replacing or copying input records with existing records of unique key values . If specified –replace, The new row replaces the existing row with the same unique key value ; If specified –ignore, The input line that copies the existing unique key value is skipped . If you do not specify these two options , An error occurs when a duplicate key value is found , And ignore the rest of the text file .
- –silent,-s: Silence mode . Output only when there is an error .
- –socket=path,-S path: When the connection localhost Socket file used when ( For the default host ).
- –user=user_name,-u user_name: When connecting to the server MySQL User name used .
- –verbose,-v: Lengthy mode , Print out the details of the program operation .
- –xml,-X: produce XML Output .
Run the help command mysqldump --help , You can get a complete list of options for a specific version .
Tips If you run mysqldump No, --quick or --opt Options ,mysqldump Load the whole result set before dumping the results
save . If you dump a large database, there may be problems , This option is enabled by default , But you can use --skip-opt Ban . If you use the most
The new version of the mysqldump Program backup data , And used to restore to the older version MySQL Server , Do not use --opt
or -e Options .
3、 ... and . mysql Command restore data
Basic grammar :
mysql –u root –p [dbname] < backup.sql
3.1. Restore a single database from a single database backup
Use root user , Back up the... From the previous exercise TRANTEST.sql The backup in the file is imported into the database , The order is as follows :
- If the backup file contains a statement to create a database , The database name does not need to be specified during recovery , As shown below
mysql -uroot -p < TRANTEST.sq
- Otherwise, you need to specify the database name , As shown below
mysql -uroot -p TRANTEST< TRANTEST.sql
3.2. Full backup recovery
mysql –u root –p < all.sql
perhaps
mysql -uroot -pxxxxxx < all.sql
After the execution ,MySQL The database has been restored all.sql All files in the database .
3.3. Restore a single library from a full backup
There may be such a need , For example, we just want to restore a certain library , But we have backup of the whole instance , At this time, we can separate the backup of a single database from the full backup .
give an example :
sed -n '/^-- Current Database: `TRANTEST`/,/^-- Current Database: `/p' all_database.sql
> TRANTEST.sql
# After the separation, we can import atguigu.sql You can restore a single library
3.4. Restore a single table from a single database backup
This demand is still quite common . For example, we know which watch is misoperated , Then you can use the method of single table recovery to restore .
give an example : We have TRANTEST Backup of the entire library , But because of student Table misoperation , You need to restore this form alone .
use TRANTEST;
# Delete student
DROP table student;
# View the tables in the Library
show tables;
# First separate the statement of creating table
cat TRANTEST.sql | sed -e '/./{H;$!d;}' -e 'x;/CREATE TABLE `student`/!d;q' > student.sql
# Then separate the insert table statement
cat TRANTEST.sql | grep --ignore-case 'insert into `student`' > StudentData.sql
Then import
mysql -uroot -p TRANTEST<student.sql
mysql -uroot -p TRANTEST<StudentData.sql
Reexamine
use TRANTEST;
SHOW TABLES;
SELECT * FROM student;
Four . The physical backup : Directly copy the entire database
Direct will MySQL Copy the database files in . This is the easiest way , And the fastest .MySQL The location of the database directory is not necessarily the same :
- stay Windows Under the platform ,MySQL 8.0 The directory where the database is stored is usually... By default “ C:\ProgramData\MySQL\MySQL Server 8.0\Data ” Or other user-defined directories ;
- stay Linux Under the platform , The database directory location is usually /var/lib/mysql/;
- stay MAC OSX Under the platform , The database directory location is usually “/usr/local/mysql/data”;
But in order to ensure the consistency of backup . Need assurance : - The way 1: Before backup , Stop the server .
- The way 2: Before backup , Execute... On related tables FLUSH TABLES WITH READ LOCK operation . In this way, when copying files in the database directory , Allow other customers to continue to query the table . meanwhile ,FLUSH TABLES Statement to ensure that all active index pages are written to the hard disk before starting the backup .
This way is convenient 、 Fast , But not the best backup method , Because the actual situation may Stop... Is not allowed MySQL The server perhaps Lock the watch , And this method Yes InnoDB Storage engine The table of does not apply . about MyISAM The table that stores the engine , This makes backup and restore easy , But it's better to restore the same version MySQL database , Otherwise, there may be different file types .
Be careful , After the physical backup , perform UNLOCK TABLES To settle the modification of the table by other customers .
explain : stay MySQL In the version number , The first number indicates the major version number , With the same major version number MySQL The database file format is the same .
Besides , You can also consider using relevant tools to realize backup . such as , MySQLhotcopy Tools .MySQLhotcopy It's a Perl Script , It USES LOCK TABLES、FLUSH TABLES and cp or scp To quickly back up the database . It's the fastest way to back up a database or a single table , But it can only run on the machine where the database directory is located , And can only back up MyISAM Type of watch . be chiefly used in mysql5.5 Before .
5、 ... and . Physical recovery : Copy directly to the database directory
step :
1) Show me how to delete the data of the specified table in the backed up database .
2) Copy the backed up database data to the data directory , And restart MySQL The server .
3) Query whether the data of related tables are recovered . You need to use the following chown operation .
requirement :
- It must be ensured that the database of the backup data and the database server to be restored have the same major version number . Because only MySQL When the main version number of the database is the same , To ensure these two MySQL The database file type is the same .
- This way is right MyISAM Table of type is more effective , about InnoDB Tables of type are not available . because InnoDB Table spaces cannot be copied directly .
- stay Linux Under the operating system , After copying to the database directory , Be sure to change the users and groups of the database into mysql, The order is as follows :
chown -R mysql.mysql /var/lib/mysql/dbname
among , Two mysql Represent groups and users respectively ;“-R” Parameters can change the users and groups of all sub files in the folder ;“dbname” The parameter represents the database directory .
Tips Linux The permission setting under the operating system is very strict . Usually ,MySQL Database only root Users and mysql user
Under group mysql Users can access , Therefore, after copying the database directory to the specified folder , Be sure to use chown The order will
The user group of the folder becomes mysql, Change the user to mysql
6、 ... and . Export and import of tables
6.1. Export of tables
6.1.1. Use SELECT…INTO OUTFILE Export text file
stay MySQL in , have access to SELECT…INTO OUTFILE Statement to export the contents of the table into a text file .
give an example : Use SELECT…INTO OUTFILE take TRANTEST In the database student Export the records in the table to a text file .
(1) Select database TRANTEST, And query student surface , The results are shown below .
USE TRANTEST;
SELECT * FROM student;
(2)mysql There are permission restrictions on the exported directory by default , That is, when using the command line for export , You need to specify a directory to operate .
Inquire about secure_file_priv value :
show global variables like '%secure%';
(3) The results above show ,secure_file_priv The value of the variable is /var/lib/mysql-files/, Set the export directory to this directory ,SQL The statement is as follows .
SELECT * FROM student INTO OUTFILE "/var/lib/mysql-files/student.txt";
(4) see /var/lib/mysql-files/account.txt` file .
cd /var/lib/mysql-files/
vim student.txt
6.1.2. Use mysqldump Command to export a text file
First, the previously generated student.txt Delete
# Delete student.txt
rm -rf student.txt
# View the files in this directory
ll
give an example 1: Use mysqldump Command will TRANTEST In the database student Export the records in the table to a text file :
mysqldump -uroot -p -T "/var/lib/mysql-files" TRANTEST student
mysqldump After the command is executed , In the specified directory /var/lib/mysql-files/ Now I have student.sql and student.txt file .
open student.sql file , Its content includes creating student Tabular CREATE sentence .
open student.txt file , Its content only includes student Table data .
give an example 2: Use mysqldump take atguigu In the database account Export table to text file , Use FIELDS Options , Commas are required between fields “,” interval , All character type field values are enclosed in double quotes :
First, the previously generated student.txt and student.sql Delete
# Delete student.txt
rm -rf student.txt
# Delete student.sql
rm -rf student.sql
# View the files in this directory
ll
mysqldump -uroot -p -T "/var/lib/mysql-files/" TRANTEST student --fields-terminated-by=',' --fields-optionally-enclosed-by='\"'
sentence mysqldump After the statement is executed successfully , Two files will appear in the specified directory student .sql and student .txt.
open student .sql file , Its content includes creating student Tabular CREATE sentence .( Same as before )
open student .txt file , Its content includes creating account The data table . As can be seen from the document , Fields are separated by commas , The value of the character type is enclosed in double quotes .
6.1.3. Use mysql Command to export a text file
give an example 1: Use mysql Statement export TRANTEST In the data student Record in table to text file :
mysql -uroot -p --execute="SELECT * FROM student;" TRANTEST > "/var/lib/mysql-files/student.txt"
give an example 2: take atguigu database account Export the records in the table to a text file , Use –veritcal Parameter displays the condition record in multiple lines :
mysql -uroot -p --vertical --execute="SELECT * FROM student;" TRANTEST >"/var/lib/mysql-files/student.txt"
open student.txt file , Its content includes creating student The data table .
give an example 3: take TRANTEST database student The records in the table are exported to xml file , Use –xml Parameters , The specific sentences are as follows .
mysql -uroot -p --xml --execute="SELECT * FROM student;" TRANTEST >"/var/lib/mysql-files/student.xml"
explain : If you want to export table data to html In file , have access to --html Options . Then you can use your browser to open .
6.2. Table import
6.2.1. Use LOAD DATA INFILE To import a text file
give an example 1:
Use SELECT…INTO OUTFILE take TRANTEST In the database student Export the records of the table to a text file
SELECT * FROM TRANTEST.student INTO OUTFILE '/var/lib/mysql-files/student.txt';
Delete student Table data :
DELETE FROM TRANTEST.student;
From a text file account.txt Recovering data in :
LOAD DATA INFILE '/var/lib/mysql-files/student.txt' INTO TABLE TRANTEST.student;
Inquire about student Table data :
select * from student;
give an example 2: Select database TRANTEST, Use SELECT…INTO OUTFILE take TRANTEST database student Export the records in the table to a text file , Use FIELDS Options and LINES Options , Commas are required between fields "," interval , All field values are enclosed in double quotes :
SELECT * FROM TRANTEST.student INTO OUTFILE '/var/lib/mysql-files/student.txt' FIELDS
TERMINATED BY ',' ENCLOSED BY '\"';
Delete student Table data :
DELETE FROM TRANTEST.student;
from /var/lib/mysql-files/student.txt Import data to student In the table :
LOAD DATA INFILE '/var/lib/mysql-files/student.txt' INTO TABLE TRANTEST.student FIELDS TERMINATED BY ',' ENCLOSED BY '\"';
Inquire about student Table data , Specifically SQL as follows :
select * from student;
6.2.2. Use mysqlimport To import a text file
give an example :
export file student.txt, Use commas between fields "," interval , The field values are enclosed in double quotes :
SELECT * FROM TRANTEST.student INTO OUTFILE '/var/lib/mysql-files/student.txt' FIELDS TERMINATED BY ',' ENCLOSED BY '\"';
Delete student Table data :
DELETE FROM TRANTEST.student;
Use mysqlimport The order will student.txt Import the contents of the file into the database TRANTEST Of student In the table :
mysqlimport -uroot -p TRANTEST '/var/lib/mysql-files/student.txt' --fields-terminated-by=',' --fields-optionally-enclosed-by='\"'
Inquire about account Table data :
select * from student;
7、 ... and . Database migration
7.1. summary
Data migration (data migration) It's about choice 、 Get ready 、 Extract and transform data , The process of transferring data permanently from one computer storage system to another . Besides , Verify the integrity of the migrated data and Decommission the old data storage , It's also considered part of the whole data migration process .
The reasons for database migration are diverse , Including server or storage device replacement 、 Maintain or upgrade , Application migration , Website integration , Disaster recovery and data center migration .
Different migration schemes may be adopted according to different requirements , But on the whole ,MySQL Data migration schemes can be roughly divided into Physical migration and Logical migration Two types of . Usually as far as possible automation By , So as to liberate human resources from tedious tasks .
7.2. Migration plan
- Physical migration
Physical migration is suitable for the overall migration of large amount of data . The advantage of using the physical migration scheme is that it is relatively fast , But it needs to be down for migration and it requires MySQL The version and configuration must be the same as the original server , It can also cause unknown problems .
Physical migration includes copying data files and using XtraBackup There are two backup tools .
Physical migration can be used between the same server , We can install the same version of database software on the new server , Create the same directory , It is suggested that the configuration file should be the same as the original database , Then copy the data file and log file from the original database , Configure file group permissions , Then use it on the new server side mysqld Command start database . - Logical migration
Logical transfer is more applicable , Whether it's Partial migration still Full migration , You can use logical migration . The most commonly used method in logical migration is through mysqldump And other backup tools .
7.3. Pay attention to migration
7.3.1. Precautions for migrating between databases of the same version
It refers to those with the same major version number MySQL Move databases between databases .
The way 1: Because before and after migration MySQL Database The main version number is the same , Therefore, database migration can be realized by copying the database directory , But physical migration is only applicable to MyISAM The engine's table . about InnoDB surface , The database cannot be backed up by directly copying files .
The way 2: The most common and safest way is to use mysqldump command Derived data , Then use... In the target database server MySQL Command import .
give an example :
#host1 Back up all databases in your machine , And migrate the database to a database named host2 On the machine
mysqldump –h host1 –uroot –p –-all-databases|
mysql –h host2 –uroot –p
In the above statement ,“|” The symbol represents the pipe , Its function is to mysqldump Backup files to mysql command ;“–all-databases” Indicates that you want to migrate all databases . In this way, the migration can be realized directly .
7.3.2. Precautions for migration between different versions of databases
for example , It turns out that many servers use 5.7 Version of MySQL database , stay 8.0 After the version is pushed out , Improved 5.7 Many defects of the version , Therefore, the database needs to be upgraded to 8.0 edition .
Between the old version and the new version MySQL Different default character sets may be used , For example, some old versions use latin1 As default character set , And the latest version of MySQL The default character set is utf8mb4. If there is Chinese data in the database , In the process of migration, we need to Modify the default character set , Otherwise, the data may not be displayed normally .
The high version of the MySQL Databases usually Compatible with lower versions , Therefore, it can be from the lower version of MySQL Migrate the database to a higher version MySQL database .
7.3.3. Precautions for migration between different databases
Migration between different databases refers to the migration from other types of databases to MySQL database , Or from MySQL Database migration to other types of databases . There is no universal solution to this migration .
Before moving , You need to understand the architecture of different databases , Compare the differences between them . Defining the same type of data in different databases Keywords may be different . for example ,MySQL The date field in is divided into DATE and TIME Two kinds of , and ORACLE The date field is only DATE;SQL Server It's in the database ntext、Image And so on ,MySQL The database does not have these data types ;MySQL Supported by ENUM and SET type , these SQL Server Database does not support .
in addition , The database vendor did not fully comply with SQL Standard to design database system , Lead to different database systems SQL sentence There are differences . for example , Microsoft SQL Server The software uses T-SQL sentence ,T-SQL It contains non-standard SQL sentence , Unable to join MySQL Of SQL Statement compatibility .
The differences between different types of databases cause mutual The difficulty of migration , These differences are actually technical barriers deliberately created by commercial companies . But the migration between different types of databases is not It's not totally impossible . for example , have access to MyODBC Realization MySQL and SQL Server Migration between .MySQL Official tools MySQL Migration Toolkit You can also migrate data between different data .MySQL Migrate to Oracle when , Need to use mysqldump Command export sql file , then , Manually change sql In the document CREATE sentence .
7.4. Migration summary
8、 ... and . Delete database processing
8.1. delete: Delete lines by mistake
- It's safer to recover data , yes Restore a backup , Or find a slave library as Temporary storage , Perform these operations on this temporary Library , Then we will confirm the data of the temporary database , Restore to the main library . If you modify the main library directly , This may result in a of data Secondary destruction .
- Of course , Aiming at the problem of preventing erroneous deletion of data , Recommendations are as follows :
- hold sql_safe_updates Parameter set to on . thus , If we forget to be in delete perhaps update Write in statement where Conditions , perhaps where If there is no index field in the condition , The execution of this statement will report an error .
- If you are sure to delete all the data in a small table , In setting up the sql_safe_updates=on Under the circumstances , Can be in delete Add to statement where Conditions , such as where id>=0.
- Before the code goes online , Must go through SQL Audit .
8.2. truncate/drop : Erasure Library / surface
programme :
In this case , To recover data , You need to use Full volume backup , Add Incremental log The way of the . This solution requires regular full backup online , And back up in real time binlog.
In the case of both conditions , If someone is at noon 12 I deleted a library by mistake , The process of data recovery is as follows :
- Take the most recent Full volume backup , Let's say that this library is available once a day , The last backup was the same day In the morning 2 spot ;
- Restore a with a backup Temporary storage ;
- From the log backup , Take it out in the morning 2 Post order log ;
- Put these logs , Except for the statement of deleting data by mistake , All applied to temporary storage .
8.3. Delay copying the standby database
If there is Very central The business of , Too long recovery time is not allowed , Consider setting up a standby database for delayed replication . The problem with the general primary and secondary replication structure is , If a table in the main database is deleted by mistake , This command will soon be sent to all slaves , In turn, all the data tables from the database are deleted by mistake .
A delayed replication standby is a special kind of standby , adopt CHANGE MASTER TO MASTER_DELAY = N command , You can specify that the standby database keep the same as the primary database N Second delay . For example, you put N Set to 3600, This means that if there is data deleted by mistake on the main database , And in 1 This misoperation order was found within hours , This command has not been executed in the standby database for delayed replication . At this time, execute on this standby database stop slave, And then through the methods introduced before , Skip misoperation command , You can recover the data you need .
8.4. Prevent deleting database by mistake / The method of table
- Account separation . The purpose of this is , Avoid writing wrong orders . such as :
- Only for business development students DML jurisdiction , But not to truncate/drop jurisdiction . And if business developers have DDL If you need it , It can be supported by developing a management system .
- Even if it's DBA Team members , It is also stipulated that only Read only account , Only use the account with update permission when necessary .
- Set up operation specifications . such as :
- Before deleting the data table , Must first Change the name of the watch operation . then , Observe for a while , Make sure there is no impact on the business before deleting this table .
- When changing the name of the watch , A fixed suffix is required for the table name ( For example, add _to_be_deleted ), Then the action of deleting the table must be performed through the management system . also , When the management system deletes a table , Only tables with fixed suffixes can be deleted .
8.5. rm: False deletion MySQL example
For a MySQL For clusters , Never mind rm Delete data 了 . Just delete the data of one of the nodes ,HA The system will start working , Choose a new main library , So as to ensure the normal operation of the whole cluster . All we have to do is recover the data on this node , Then connect to the whole cluster .
Nine . appendix :MySQL Common commands
9.1. mysql
The mysql Don't mean mysql service , But to mysql Client tools .
grammar :
mysql [options] [database]
9.1.1. Connection options
# Parameters :
-u, --user=name Specify user name
-p, --password[=name] Specified password
-h, --host=name Specify the server IP Or domain name
-P, --port=# Specify the connection port
# Example :
mysql -h 127.0.0.1 -P 3306 -u root -p
mysql -h127.0.0.1 -P3306 -uroot -p password
9.1.2. Execution Options
-e, --execute=name perform SQL Statement and exit
This option is available in Mysql Client execution SQL sentence , Instead of connecting to MySQL The database then executes , For some batch scripts , This is especially convenient .
# Example :
mysql -uroot -p TRANTEST -e "select * from student";
9.2. mysqladmin
mysqladmin Is a client program that performs administrative operations . It can be used to check the configuration and current state of the server 、 Create and delete databases, etc .
Can pass : mysqladmin --help Command to view help documents
# Example :
mysqladmin -uroot -p create 'test01';
mysqladmin -uroot -p drop 'test01';
mysqladmin -uroot -p version;
9.3. mysqlbinlog
Because the binary log file generated by the server is saved in binary format , So if you want to check the text format of these texts , Will be used to mysqlbinlog Log management tools .
grammar :
mysqlbinlog [options] log-files1 log-files2 ...
# Options :
-d, --database=name : Specify database name , Only the specified database related operations are listed .
-o, --offset=# : Ignore the previous in the log n Line command .
-r,--result-file=name : Output the output text format log to the specified file .
-s, --short-form : Show simple format , Omit some information .
--start-datatime=date1 --stop-datetime=date2 : All logs within the specified date interval .
--start-position=pos1 --stop-position=pos2 : All logs within the specified location interval .
9.4. mysqldump
mysqldump Client tools are used to back up databases or migrate data between different databases . The backup includes creating tables , And insert the SQL sentence .
grammar :
mysqldump [options] db_name [tables]
mysqldump [options] --database/-B db1 [db2 db3...]
mysqldump [options] --all-databases/-A
9.4.1. Connection options
# Parameters :
-u, --user=name Specify user name
-p, --password[=name] Specified password
-h, --host=name Specify the server IP Or domain name
-P, --port=# Specify the connection port
9.4.2. Output content options
# Parameters :
--add-drop-database Add... Before each database creation statement Drop database sentence
--add-drop-table Add... Before each table creation statement Drop table sentence , Default on ; Don't open (--
skip-add-drop-table)
-n, --no-create-db Do not include database creation statements
-t, --no-create-info Create statement without data table
-d --no-data No data
-T, --tab=name Automatically generate two files : One .sql file , Statement to create a table structure ;
One .txt file , Data files , amount to select into outfile
# Example :
mysqldump -uroot -p db01 tb_book --add-drop-database --add-drop-table > a
mysqldump -uroot -p -T /tmp test city
9.5. mysqlimport/source
mysqlimport Is the client data import tool , Used to import mysqldump Add -T The text file exported after the parameter .
grammar :
mysqlimport [options] db_name textfile1 [textfile2...]
Example :
mysqlimport -uroot -p test /tmp/city.txt
If you need to import sql file , have access to mysql Medium source Instructions :
source /root/tb_book.sql
9.6. mysqlshow
mysqlshow Client object finder , Used to quickly find which databases exist 、 Tables in the database 、 A column or index in a table .
grammar :
mysqlshow [options] [db_name [table_name [col_name]]]
Parameters :
--count Display statistics of databases and tables ( database , surface You can not specify )
-i Display the status information of the specified database or table
Example :
# Query the number of tables in each database and the number of records in the table
mysqlshow -uroot -p --count
# Inquire about test The fields in each table in the library , And the number of lines
mysqlshow -uroot -p TRANTEST --count
# Inquire about TRANTEST In the library student Details of the table
mysqlshow -uroot -p TRANTEST student --count
边栏推荐
- Not registered via @enableconfigurationproperties, marked (@configurationproperties use)
- 评估方法的优缺点
- MySQL实战优化高手10 生产经验:如何为数据库的监控系统部署可视化报表系统?
- Installation de la pagode et déploiement du projet flask
- 14 medical registration system_ [Alibaba cloud OSS, user authentication and patient]
- Contest3145 - the 37th game of 2021 freshman individual training match_ C: Tour guide
- Installation of pagoda and deployment of flask project
- Flash operation and maintenance script (running for a long time)
- MySQL实战优化高手04 借着更新语句在InnoDB存储引擎中的执行流程,聊聊binlog是什么?
- MySQL底层的逻辑架构
猜你喜欢
软件测试工程师必备之软技能:结构化思维
Carolyn Rosé博士的社交互通演讲记录
UnicodeDecodeError: ‘utf-8‘ codec can‘t decode byte 0xd0 in position 0成功解决
Super detailed steps for pushing wechat official account H5 messages
华南技术栈CNN+Bilstm+Attention
Record the first JDBC
17 医疗挂号系统_【微信支付】
软件测试工程师必备之软技能:结构化思维
jar运行报错no main manifest attribute
Cmooc Internet + education
随机推荐
百度百科数据爬取及内容分类识别
MySQL combat optimization expert 10 production experience: how to deploy visual reporting system for database monitoring system?
Canoe CAPL file operation directory collection
MySQL实战优化高手04 借着更新语句在InnoDB存储引擎中的执行流程,聊聊binlog是什么?
Good blog good material record link
Configure system environment variables through bat script
MySQL combat optimization expert 12 what does the memory data structure buffer pool look like?
解决在window中远程连接Linux下的MySQL
高并发系统的限流方案研究,其实限流实现也不复杂
在jupyter NoteBook使用Pytorch进行MNIST实现
Complete web login process through filter
Several errors encountered when installing opencv
Windchill配置远程Oracle数据库连接
西南大学:胡航-关于学习行为和学习效果分析
Solve the problem of remote connection to MySQL under Linux in Windows
C miscellaneous dynamic linked list operation
Zsh configuration file
Cmooc Internet + education
Vscode common instructions
Super detailed steps for pushing wechat official account H5 messages