当前位置:网站首页>Realize the scheduled backup of MySQL database in Linux environment through simple script (mysqldump command backup)
Realize the scheduled backup of MySQL database in Linux environment through simple script (mysqldump command backup)
2022-07-29 05:56:00 【People with different feelings】
1、mysqldump command
mysqldump yes mysql Utility for transferring storage databases . It mainly produces a SQL Script , It contains the commands necessary to recreate the database from scratch CREATE TABLE INSERT etc. .
command :mysqldump -h The host address -u user name -p Database password Database name surface 1 surface 2 > file name
If the user name requires a password , You need to enter a password check after this command is executed ; If the database user name does not require a password , Do not add “-p” Parameters , The import time is the same . Note that the entered user name needs to have the operation permission of the corresponding database , Otherwise, data cannot be exported . Because it is for system maintenance and export of all databases , Generally we use root And other super user permissions .
Other command references
Backup remote MySQL Database commands
mysqldump -hhostname -uusername -ppassword databasename > backupfile.sql
Backup MySQL The database is backed up in the form of deleted tables MySQL The database is in the form of deleted tables , The backup can overwrite the existing database without manually deleting the original database .
mysqldump ---add-drop-table -uusername -ppassword databasename > backupfile.sql
Direct will MySQL Database compression backup
mysqldump -hhostname -uusername -ppassword databasename | gzip > backupfile.sql.gz
Backup MySQL A database ( some ) surface
mysqldump -hhostname -uusername -ppassword databasename specific_table1 specific_table2 > backupfile.sql
Backup multiple files at the same time MySQL database
mysqldump -hhostname -uusername -ppassword --databases databasename1 databasename2 databasename3 > multibackupfile.sql
Just back up the database structure
mysqldump --no-data --databases databasename1 databasename2 databasename3 > structurebackupfile.sql
Back up all databases on the server
mysqldump --all-databases allbackupfile.sql
Restore MySQL Database commands
mysql -hhostname -uusername -ppassword databasename < backupfile.sql
Restore compressed MySQL database
gunzip < backupfile.sql.gz | mysql -uusername -ppassword databasename
2、crontab command
crontab Commands are used to set the instructions that are executed periodically , And store it in /etc/crontab file , For later reading and execution .cron The system schedules the process , You can use it to run jobs during off peak load periods every day , Or run at different times of the week or month ,cron It is the main scheduling process of the system , Jobs can be run without human intervention .
Please refer to the details 《Linux Crontab Timing task 》
crontab Use
crontab [-u username] // Omitting the user table indicates the operation of the current user crontab
-e ( Edit the sheet )
-l ( List the orders in the worksheet )
-r ( Delete the work )
We use it crontab -e Enter the current user's worksheet edit , Is common vim Interface . Each line is a command .
crontab The order of is Time + action , The time is divided 、 when 、 Japan 、 month 、 On Friday , Operators have 
Example :
[[email protected] soft]# crontab -l
0 2 * * * bash /usr/soft/mysql_backup.sh? # Every morning 2 Click to execute once
*/1 * * * * bash /usr/soft/mysql_backup.sh? # Execute every minute
3、 practice
Through the previous understanding , We basically know mysql Export command mysqldump and Linux Timing command crontab The use of , Now let's try to realize the command of regularly backing up the specified tables in the specified database .
1、 Backup scripts
First , establish mysql_backup.sh file , Define the script for backing up the database , The implementation is as follows :
#!/bin/bash
# Backup location
backup_dir='/usr/data/backup/mysql/'
# Get the current time
current_time=$(date +'%Y-%m-%d_%H%M%S')
# take backup_dir Combined with time , Add a suffix
filepath=$backup_dir$current_time'.sql.gz'
# database information , Configure database account password
s_ip='127.0.0.1'
username='root'
password='xxx'
source_database='xxx'
echo "-----------------------"$(date +%F%r)" Operation start --------------------------------"
echo $(date +%F%r)" Start data backup ..."
# 2>/dev/null Can suppress warning messages
mysqldump -h${
s_ip} -P3306 -u ${
username} -p"${password}" ${
source_database} table1 table2 table3 | gzip > $filepath
echo $(date +%F%r)" Complete synchronization ..."
The above script implements , Backup s_ip Host computer source_database database , And only backup table1、table2、table3 Three data sheets , And gzip Format compression , The storage path is backup_dir.
2、 exception handling
Be careful : appear “/bin/bash^M: bad interpreter: No such file or directory” Report errors
Because in general , The script will be in windows Write... In the environment , This is the time , Secondary upload to Linux System time , There may be “/bin/bash^M: bad interpreter: No such file or directory” error , This is because shell The script file is dos Format , That is, each line ends with \r\n To mark , and unix Format file line ends with \n To mark . terms of settlement :
- Look at the format of the script : cat -A filename
Judging from the display results ,dos Format file line ends with ^M$,unix Format file line ends with $. - Change the format of the script :
vi filename Open file , perform : set ff=unix Set the file to unix, And then execute :wq, Save as unix Format . - Look at the format of the script : cat -A filename
Judging from the display results ,dos Format file line ends with ^M$,unix Format file line ends with $.
The execution script appears :“-bash: ./mysql_backup.sh: Permission denied” abnormal
This error is reported , The script is not authorized , The order is as follows :
chmod u+x mysql_backup.sh
The execution script appears :“./mysql_backup.sh: line 19: /usr/data/backup/mysql/2022-04-28_150941.sql.gz: No such file or directory” abnormal
The error is , The path in the backup script , stay Linux There is no... In the system , This is the time , You need to create the corresponding directory , The file is generated automatically .
3、 Create a scheduled task
Complete the above steps , The script is created , And can be used normally , The following is to create a scheduled task .
stay Linux In the system , perform “crontab -e” command , Enter the scheduled task editing interface , Editing requires timed commands , As shown below :
After editing and saving , Check the following tasks :
边栏推荐
- “山东大学移动互联网开发技术教学网站建设”项目实训日志二
- 学习、研究编程之道
- 量化开发必掌握的30个知识点【什么是Level-2数据】
- The Platonic metauniverse advocated by musk has long been verified by platofarm
- Training log 7 of the project "construction of Shandong University mobile Internet development technology teaching website"
- DeFi 2.0的LaaS协议,重振DeFi赛道发展的关键
- Process management of day02 operation
- 一文读懂Move2Earn项目——MOVE
- The completely decentralized programming mode does not need servers or IP, just like a aimless network extending everywhere
- How can Plato obtain premium income through elephant swap in a bear market?
猜你喜欢

centos7 静默安装oracle

Ribbon学习笔记二

July 28 ens/usd Value Forecast: ENS attracts huge profits

Laravel swagger add access password

Plato farm is expected to further expand its ecosystem through elephant swap

"Shandong University mobile Internet development technology teaching website construction" project training log I

iSCSI vs iSER vs NVMe-TCP vs NVMe-RDMA

Huawei 2020 school recruitment written test programming questions read this article is enough (Part 1)

并发编程学习笔记 之 工具类Semaphore(信号量)

Laravel service container (Application of context binding)
随机推荐
Countdown of the uniapp component (such as the countdown to reading the agreement and the countdown to completing learning)
Dao race track is booming. What are the advantages of m-dao?
My ideal job, the absolute freedom of coder farmers is the most important - the pursuit of entrepreneurship in the future
Fantom (FTM) prices will soar by 20% in the next few days
Performance comparison | FASS iSCSI vs nvme/tcp
day02 作业之文件权限
C# 判断用户是手机访问还是电脑访问
Synchronous development with open source projects & codereview & pull request & Fork how to pull the original warehouse
并发编程学习笔记 之 工具类CountDownLatch、CyclicBarrier详解
Tear the ORM framework by hand (generic + annotation + reflection)
Strategic cooperation with many institutions shows the strength of the leading company of platofarm yuancosmos
完全去中心化的编程模式,不需要服务器,也不需要ip,就像一张漫无目的的网络、四处延伸
File文件上传的使用(2)--上传到阿里云Oss文件服务器
Thinkphp6 output QR code image format to solve the conflict with debug
如何零代码制作深度学习的趣味app(适合新手)
Laravel swagger add access password
“山东大学移动互联网开发技术教学网站建设”项目实训日志五
并发编程学习笔记 之 ReentrantLock实现原理的探究
rsync+inotyfy实现数据单项监控实时同步
“山东大学移动互联网开发技术教学网站建设”项目实训日志六