使用Java备份mysql数据库

使用java程序生成.sql文件备份数据库。

application.yml

在yml文件中配置需要备份的数据库信息以及备份文件路径

server:
  port: 8180

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/db_robot_check?characterEncoding=utf8&serverTimezone=GMT&useSSL=false&allowMultiQueries=true

backup:
  datasource:
    ip: 127.0.0.1
    db: db_robot_check   #定义数据库名
    # table: ntcp_data_      #定义数据库表名
    port: 3306
    username: root
    password: 123456
  backupDay: 0              #备份多少天前的数据库数据
  deleteDay: 2              #删除多少天前数据库备份文件
  backupPath: D:\\JavaCode\\testmaven29MySqlBasckup\\backup\\

备份数据库

执行命令

mysqldump -h127.0.0.1 -p3306 -uroot -p123456 --default-character-set=utf8 db_robot_check

public class DbUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(DbUtil.class);

    /**
     * 备份数据库
     * @param ip
     * @param host
     * @param username
     * @param password
     * @param databaseName
     * @param savePath
     * @param fileName
     */
    public static void exportDatabaseTool(String ip,String host,String username,String password,String databaseName,String savePath,String fileName){
        PrintWriter printWriter = null;
        BufferedReader bufferedReader = null;
        try {
            File saveFile = new File(savePath);
            if (!saveFile.exists()) {
                // 目录不存在创建新的文件夹
                saveFile.mkdirs();
            }
            if (!savePath.endsWith(File.separator)) {
                savePath = savePath+File.separator;
            }
            printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(savePath+fileName),"utf-8"));
            Process process = Runtime.getRuntime().exec(" mysqldump -h"+ip+" -p"+host+" -u"+username+" -p"+password+" --default-character-set=utf8 "+databaseName);
            InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(),"utf8");
            bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                printWriter.println(line);
            }
            printWriter.flush();
            LOGGER.info("已备份数据库");
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(e.toString());
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (printWriter != null) {
                    printWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

执行

利用quartz定时调用备份数据库方法

/**
 * @author huangzixiao
 * @Description
 * @date 2023/5/11
 */
public class QuartzSqlBackup extends QuartzJobBean {

    /**
     * 数据库用户名
     */
    @Value("${backup.datasource.username}")
    private String user;

    /**
     * 数据库密码
     */
    @Value("${backup.datasource.password}")
    private String password;

    /**
     * 数据库地址
     */
    @Value("${backup.datasource.ip}")
    private String ip;

    /**
     * 数据库
     */
    @Value("${backup.datasource.db}")
    private String db;

    /**
     * 表名
     */
    //@Value("${backup.datasource.table}")
    //private String table;

    /**
     * 备份多少天前的数据库数据
     */
    @Value("${backup.backupDay}")
    private String backupDay;

    /**
     * 删除多少天前数据库备份
     */
    @Value("${backup.deleteDay}")
    private String deleteDay;

    /**
     * 备份路径
     */
    @Value("${backup.backupPath}")
    private String backupPath;

    private static SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
    /**
     * Execute the actual job. The job data map will already have been
     * applied as bean property values by execute. The contract is
     * exactly the same as for the standard Quartz execute method.
     *
     * @param context
     * @see #execute
     */
    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        // 定时备份数据库
        // 指定名称
        String sqlFileName = db+"_sql_back_up_"+sf.format(new Date())+".sql";

        DbUtil.exportDatabaseTool(ip,"3306",user,password,db,backupPath,sqlFileName);
        // 删除过期时间的文件
        FileUtil.deleteOverTimeFile(backupPath);
    }
}

为了防止sql文件过多,定期删除过期文件

public class FileUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(FileUtil.class);
    public static void deleteOverTimeFile(String filePath) {
        // 指定时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.MINUTE,-10);
        // 判断文件夹是否为空或不存在
        File deleteFilePath = new File(filePath);
        if (deleteFilePath.exists()) {
            File[] files = deleteFilePath.listFiles();
            if (files!=null&&files.length>0) {
                for (File file : files) {
                    if (new Date(file.lastModified()).before(calendar.getTime())) {
                        LOGGER.info("删除文件:"+file.getName());
                        file.delete();
                    }
                }
            }
        }
    }
}

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以使用以下步骤来实现Java语言备份MySQL数据库: 1. 导入MySQL JDBC驱动程序 Java程序需要使用MySQL JDBC驱动程序来连接和操作MySQL数据库。可以从MySQL官方网站下载并导入驱动程序。 2. 创建连接 使用JDBC驱动程序创建与MySQL数据库的连接。可以使用以下代码来创建连接: ``` String driver = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/mydatabase"; String user = "root"; String password = "mypassword"; Class.forName(driver); Connection conn = DriverManager.getConnection(url, user, password); ``` 其中,`driver`是JDBC驱动程序的类名,`url`是连接字符串,`user`和`password`是数据库的用户名和密码。 3. 执行备份命令 使用Java程序执行备份命令。可以使用以下代码来执行备份命令: ``` String backupPath = "/path/to/backup.sql"; String command = "mysqldump --opt --user=" + user + " --password=" + password + " --host=localhost mydatabase > " + backupPath; Process process = Runtime.getRuntime().exec(command); int exitStatus = process.waitFor(); if(exitStatus == 0) { System.out.println("Backup successful"); } else { System.out.println("Backup failed"); } ``` 其中,`backupPath`是备份文件的路径,`command`是备份命令。使用`Runtime.getRuntime().exec()`方法执行命令,并使用`process.waitFor()`方法等待命令执行完成。 4. 关闭连接 备份完成后,使用Java程序关闭与MySQL数据库的连接。可以使用以下代码来关闭连接: ``` conn.close(); ``` 这些步骤可以实现Java语言备份MySQL数据库。需要注意的是,备份命令需要正确设置MySQL用户名、密码、主机和数据库名称。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值