使用mysqldump备份MySQL数据库到本地

Windows环境下

public void windowsDump(String dir, String host, String port, String username, String password, String databasename) throws Exception {
        File file = new File(dir);
        if (!file.exists()) {
            file.mkdir();
        }
        String sqlname = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());
        File datafile = new File(file + File.separator + sqlname + ".sql");
        if (datafile.exists()) {
            System.out.println(sqlname + "文件名已存在,请更换");
            return;
        }
        //一般mysqldump 在 MySQL 安装目录的 bin 文件夹下
        String mysqldumpPath = "C:\\Program Files\\MySQL\\MySQL Server 8.0\\bin\\mysqldump.exe";
        String command = "cmd /c \"" + mysqldumpPath + "\" -h" + host + " -P" + port + " -u " + username + " -p" + password + " " + databasename + " > " + datafile;
        Process exec = Runtime.getRuntime().exec(command);
        if (exec.waitFor() == 0) {
            System.out.println("数据库备份成功,备份路径为:" + datafile);
        }
    }

Linux环境下

public void linuxDump(String dir, String host, String port, String username, String password, String databasename) throws Exception {
        File file = new File(dir);
        if (!file.exists()) {
            file.mkdir();
        }
        String sqlname = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());
        File datafile = new File(file + File.separator + sqlname + ".sql");
        if (datafile.exists()) {
            System.out.println(sqlname + "文件名已存在,请更换");
            return;
        }
        Process exec = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", "/usr/bin/mysqldump -h" + host + " -P" + port + " -u " + username + " -p" + password + " " + databasename + " > " + datafile});
        if (exec.waitFor() == 0) {
            System.out.println("数据库备份成功,备份路径为:" + datafile);
        }
    }

参考

若依系统定时备份数据库功能的实现
Springboot ruoyi配置mysql备份定时任务

Logo

一站式 AI 云服务平台

更多推荐