Java如何在Ubuntu中备份MySQL数据库?

什么是MySQL

MySQL是一个开源RDBMS (关系数据库管理系统)。顾名思义,它使用SQL (结构化查询语言)访问和处理数据。MySQL已被广泛用于存储和管理从简单的Web应用程序到企业级应用程序的数据。

在每个应用程序中,重要的数据要求我们定期备份数据,以防止数据丢失(例如,由硬件崩溃引起的丢失)。在本文中,我将向您展示如何手动备份数据库以及如何使用脚本cron作业结合使用以自动运行该过程。

使用mysqldump

要在MySQL中创建数据库备份,我们可以使用以下mysqldump命令。使用此命令的示例语法为:

mysqldump -u username -p database_to_backup > backup_file_name.sql

如果需要还原数据库,则可以使用以下命令:

mysql -u username -p database_to_restore < backup_file_name.sql

如果没有该数据库,则可能需要先创建数据库,然后才能执行该命令。

saturn@ubuntu:~$ mysql -u root -p
CREATE DATABASE database_to_restore;
exit;

创建备份脚本

首先,让我们创建将用于执行备份过程的MySQL用户帐户。使用mysql -u root -p命令登录到MySQL 。输入并执行以下命令来创建backupuser。

grant lock tables, select, show view on kodejava.* to 'backupuser'@'localhost' identified by 'backuppasswd';
flush privileges;

使用exit命令从MySQL退出,并backup.sh使用您喜欢的编辑器创建以下备份脚本。例如,您可以使用nano或vim创建文件。

#!/bin/sh
BACKUP_HOME="/home/saturn/backup"

cd $BACKUP_HOME
directory="$(date +%Y%m%d)"

if [ ! -d "$directory" ]; then
    mkdir $directory
fi

backupdir="$BACKUP_HOME/$directory"
backup="nhooo-$(date +%Y%m%d%H%M%S)"

mysqldump -ubackupuser -pbackuppasswd --opt nhooo > $backupdir/$backup.sql

cd $directory
tar -czf $backup.tar.gz $backup.sql
rm $backup.sql

要使backup.sh文件可执行,您需要运行chmod +x backup.sh命令。

使用Crontab创建调度程序

crontab命令用于命令调度要在预定时间周期性地执行。它将作为后台进程运行,而无需用户干预。这些作业通常称为cron作业,并且这些作业将以创建cron作业的用户身份运行。

在下面的示例中,我们注册了一个cron作业来每天凌晨12:00执行脚本。要编辑cron作业类型crontab -e,这将打开crontab文件。

saturn@ubuntu:~$ crontab -e
no crontab for saturn - using an empty one

Select an editor.  To change later, run 'select-editor'.
  1. /bin/ed
  2. /bin/nano        <---- easiest
  3. /usr/bin/vim.basic
  4. /usr/bin/vim.tiny

Choose 1-4 [2]:

选择一个编辑器来编辑crontab,通过输入编辑器的编号来选择。最简单的一个是nano,但是如果你喜欢,你也可以使用vim。

您将看到一个空的crontab文件,其中将显示以下注释消息:

# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5a.mevery week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h  dom mon dow   command

转到文件末尾并写入以下条目以注册cron作业。在下面的示例中,我们注册一个cron作业以backup.sh每天12:00M执行脚本。

# m h  dom mon dow   command
  0 0   *   *   *    /home/saturn/backup.sh

保存文件后,可以使用crontab -l命令列出已注册的cron作业。如果您想了解有关crontab的更多信息,请访问crontab guru网站。