当前位置:网站首页>How to gracefully realize regular backup of MySQL database (glory Collection Edition)
How to gracefully realize regular backup of MySQL database (glory Collection Edition)
2022-07-24 21:12:00 【Dragon back ride Shi】

Catalog
One 、mysqldump Command backup data
1、mysqldump Common operation examples
2、 Restore MySQL Backup content
3、 To write BASH Maintain a fixed number of backup files
Preface
In the process of manipulating data , May cause data errors , Even the database crashed , And effective scheduled backup can well protect the database . This article mainly describes several methods to MySQL Back up the database regularly .
One 、mysqldump Command backup data
stay MySQL It provides a convenient tool for command line to export database data and files mysqldump, We can directly export the database content through the command line dump, First of all, let's have a brief understanding of mysqldump Command usage :
#MySQLdump Commonly used
mysqldump -u root -p --databases database 1 database 2 > xxx.sql1、mysqldump Common operation examples
1. Back up the data and structure of all databases
mysqldump -uroot -p123456 -A > /data/mysqlDump/mydb.sql2. Back up the structure of all databases ( Add -d Parameters )
mysqldump -uroot -p123456 -A -d > /data/mysqlDump/mydb.sql3. Back up all database data ( Add -t Parameters )
mysqldump -uroot -p123456 -A -t > /data/mysqlDump/mydb.sql4. Back up the data and structure of a single database (, Database name mydb)
mysqldump -uroot-p123456 mydb > /data/mysqlDump/mydb.sql5. Backing up the structure of a single database
mysqldump -uroot -p123456 mydb -d > /data/mysqlDump/mydb.sql6. Backing up data from a single database
mysqldump -uroot -p123456 mydb -t > /data/mysqlDump/mydb.sql7. Backing up data and structure of multiple tables ( data , The separate backup method of the structure is the same as above )
mysqldump -uroot -p123456 mydb t1 t2 > /data/mysqlDump/mydb.sql8. Backing up multiple databases at a time
mysqldump -uroot -p123456 --databases db1 db2 > /data/mysqlDump/mydb.sql2、 Restore MySQL Backup content
There are two ways to restore , The first is in MySQL Command line , The second is to use SHELL Line complete restore
1. On the system command line , Enter the following to restore :
mysql -uroot -p123456 < /data/mysqlDump/mydb.sql2. Log in to mysql In the system , adopt source Command to find the file in the corresponding system to restore :
mysql> source /data/mysqlDump/mydb.sqlstay Linux in , Usually use BASH The script writes what needs to be executed , Plus regular command execution crontab Realize automatic log generation .
The following code functions are for mysql Make a backup , coordination crontab, The backup content is about one month (31 God ) Every day in mysql Database records .
3、 To write BASH Maintain a fixed number of backup files
stay Linux in , Use vi perhaps vim Write the script and name it :mysql_dump_script.sh
#!/bin/bash
# Save the number of backup , Backup 31 Day data
number=31
# Backup save path
backup_dir=/root/mysqlbackup
# date
dd=`date +%Y-%m-%d-%H-%M-%S`
# Backup tools
tool=mysqldump
# user name
username=root
# password
password=TankB214
# The database to be backed up
database_name=edoctor
# If the folder does not exist, create
if [ ! -d $backup_dir ];
then
mkdir -p $backup_dir;
fi
# Simple writing mysqldump -u root -p123456 users > /root/mysqlbackup/users-$filename.sql
$tool -u $username -p$password $database_name > $backup_dir/$database_name-$dd.sql
# Write create backup log
echo "create $backup_dir/$database_name-$dd.dupm" >> $backup_dir/log.txt
# Find the backup that needs to be deleted
delfile=`ls -l -crt $backup_dir/*.sql | awk '{print $9 }' | head -1`
# Determine whether the current number of backups is greater than $number
count=`ls -l -crt $backup_dir/*.sql | awk '{print $9 }' | wc -l`
if [ $count -gt $number ]
then
# Delete the earliest generated backup , Only keep number Number of backups
rm $delfile
# Write delete file log
echo "delete $delfile" >> $backup_dir/log.txt
fiThe main meaning of the above code is as follows :
1. First, set the parameters , for example number The maximum number of backups required , Backup path , user name , Password etc. .
2. perform mysqldump Command save backup file , And print the operation to log.txt Mark the operation log in .
3. Define files to delete : adopt ls Command to get the ninth column , That is, the list of documents , Then define the file to be deleted with the latest operation time through the implementation .
4. Define the number of backups : adopt ls Command plus , Statistics to sql The number of lines in the ending file .
5. If the file exceeds the limit size , Delete the first sql file
3.1、 Use crontab Execute backup scripts on a regular basis
stay Linux in , Periodic tasks are usually performed by cron This daemons will handle [ps -ef|grep cron].cron Read one or more configuration files , These configuration files contain the command line and its call time .
cron The configuration file for is called “crontab”, yes “cron table” Abbreviation .
3.2、cron service
cron It's a Liunx Next The timing tool of , You can run a job without human intervention .
service crond start // Start the service
service crond stop // Close the service
service crond restart // Restart the service
service crond reload // service crond reload
service crond status // View service status 3.3、crontab grammar
crontab The command is used to install 、 Delete or list for driving cron The table of the background process . The user places the sequence of commands to be executed in crontab File to get execution . Every user can have their own crontab file ./var/spool/cron Under the crontab Files cannot be created or modified directly . The crontab The document is passed crontab Command created .
stay crontab How to input the command and time to execute in the file . Each line in the file contains six fields , The first five fields specify when the command will be executed , The last domain is the command to be executed .
Separate each field with a space or tab .
The format is as follows :
minute hour day-of-month month-of-year day-of-week commands
Legal value 00-59 00-23 01-31 01-12 0-6 (0 is sunday)Besides numbers, there are several special symbols "*"、"/" and "-"、",",* Represents all numbers in the range of values ,"/" Represents the meaning of each ,"/5" each 5 A unit of ,"-" Represents from a number to a number ,"," Separate several discrete numbers .
-l Display the current... On the standard output crontab.
-r Delete the current crontab file .
-e Use VISUAL perhaps EDITOR The editor that the environment variable refers to edits the current crontab file . When the end editor leaves , The edited file will be installed automatically .
3.5、 establish cron Script
First step : Write cron Script files , Name it mysqlRollBack.cron.
15,30,45,59 * * * * echo "xgmtest....." >> xgmtest.txt Express , every other 15 minute , Execute the print once command
The second step : Add timing task . Carry out orders “crontab crontest.cron”. Get it done
The third step :"crontab -l" Check if the scheduled task is successful or check /var/spool/cron Whether to generate corresponding cron Script
Be careful : This operation is to replace the user directly crontab, Instead of adding .
Execute the scheduled task script written on a regular basis ( Remember to give it first shell Script execution permission )
0 2 * * * /root/mysql_backup_script.shSubsequent use crontab Command the timing script written by the periodic instruction
crontab mysqlRollback.cronThen check whether the scheduled task has been created through the command :
attach crontab Use example of :
1. Every day in the morning 6 spot
0 6 * * * echo "Good morning." >> /tmp/test.txt // Pay attention to simplicity echo, No output can be seen from the screen , because cron Put any output email To root The mailbox of .2. Every two hours
0 */2 * * * echo "Have a break now." >> /tmp/test.txt3. evening 11 Point to morning 8 Every two hours between and eight in the morning
0 23-7/2,8 * * * echo "Have a good dream" >> /tmp/test.txt4. Monthly 4 And every Monday to Wednesday morning 11 spot
0 11 4 * 1-3 command line5.1 month 1 Day in the morning 4 spot
0 4 1 1 * command line SHELL=/bin/bash PATH=/sbin:/bin:/usr/sbin:/usr/bin MAILTO=root // If something goes wrong , Or data output , The data is sent to this account as an email HOME=/6. Hourly execution /etc/cron.hourly Script inside
01 * * * * root run-parts /etc/cron.hourly7. Daily execution /etc/cron.daily Script inside
02 4 * * * root run-parts /etc/cron.daily8. Every week /etc/cron.weekly Script inside
22 4 * * 0 root run-parts /etc/cron.weekly9. Every month /etc/cron.monthly Script inside
42 4 1 * * root run-parts /etc/cron.monthlyBe careful : "run-parts" This parameter , If you remove this parameter , You can then write the name of a script to run , Not the folder name .
10. Every afternoon 4 spot 、5 spot 、6 Dot 5 min、15 min、25 min、35 min、45 min、55 min To execute an order .
5,15,25,35,45,55 16,17,18 * * * command11. Every Monday , 3、 ... and , Five afternoons 3:00 The system enters the maintenance state , Restart the system .
00 15 * * 1,3,5 shutdown -r +512. Hourly 10 branch ,40 Execute... In the user directory innd/bbslin This instruction :
10,40 * * * * innd/bbslink13. Hourly 1 Execute... In the user directory bin/account This instruction :
Here's a screenshot of my test every minute , The corresponding code is as follows :
* * * * * /root/mysql_backup_script.sh Effect screenshots :
Among them log.txt Record the detailed operation log of the backup :

Only when you start , You will reach your ideal and destination , Only when you work hard ,
You will achieve brilliant success , Only when you sow , You will gain something . Only pursue ,
To taste the taste of success , Sticking to yesterday is called foothold , Sticking to today is called enterprising , Sticking to tomorrow is called success . Welcome all friends to praise + Collection !!!

边栏推荐
- What does software testing need to learn?
- 93. Recursive implementation of combinatorial enumeration
- Merge sort
- Go language structure
- Selenium is detected as a crawler. How to shield and bypass it
- [feature transformation] feature transformation is to ensure small information loss but high-quality prediction results.
- Lazily doing nucleic acid and making (forging health code) web pages: detained for 5 days
- Preview and save pictures using uni app
- 96. Strange tower of Hanoi
- [jzof] 05 replace spaces
猜你喜欢

Summary of yarn capacity scheduler
![[jzof] 06 print linked list from end to end](/img/c7/c2ac4823b5697279b81bec8f974ea9.png)
[jzof] 06 print linked list from end to end

Eight transformation qualities that it leaders should possess

Drive subsystem development

Two methods of how to export asynchronous data

Together again Net program hangs dead, a real case analysis of using WinDbg

Let's make a nice monthly temperature map of China with ArcGIS

90% of people don't know the most underestimated function of postman!
![[basic data mining technology] KNN simple clustering](/img/df/f4a3d9b8a636ea968c98d705547be7.png)
[basic data mining technology] KNN simple clustering

Upgrade appium automation framework to the latest 2.0
随机推荐
Summary of communication with customers
How to learn automated testing? Can you teach yourself?
93. Recursive implementation of combinatorial enumeration
Redis (12) -- redis server
Oracle 19C datagruad replication standby rman-05535 ora-01275
Leetcode skimming -- bit by bit record 018
Solution: 2003 cant connect to MySQL server on * * * * and use near 'identified by' * * * * 'with grant option' at
A simple method of converting SVG to PDF
Mysql database query is so slow. Besides index, what else can it do?
Alibaba sentinel basic operation
Do you want to verify and use the database in the interface test
Cloud native observability tracking technology in the eyes of Baidu engineers
[JVM] selection of garbage collector
Scientific computing toolkit SciPy Fourier transform
250 million, Banan District perception system data collection, background analysis, Xueliang engineering network and operation and maintenance service project: Chinatelecom won the bid
Mitmproxy tampering with returned data
Baidu classic interview question - determine prime (how to optimize?)
96. Strange tower of Hanoi
Shengbang security rushes to the scientific innovation board: Qianxin is its largest customer (55.87 million); Its three-year revenue is 460 million, net profit is 95.04 million, and R & D investment
[learning notes] agc008