dbbackup.java 3.21 KB
package com.huaheng.framework.dbbackups;

import com.huaheng.common.exception.service.ServiceException;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.text.SimpleDateFormat;

/**
 * @author huaheng
 * 数据库备份类
 * 使用前提是运行本机装有mysql客户端,目前仅支持windows系统使用,使用前需要将Mysql/bin文件夹中的mysqldump文件放到C盘根目录下。
 * 文件夹父级目录不能有空格等特殊符号,否则备份失败
 */
public class dbbackup {


    @Test
    public void dbbackup() {
        String hostIP = "172.16.29.45";
        String userName = "root";
        String password = "hhsoftware";
        String savePath = "D:\\DBbackups\\";
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String Date = formatter.format(currentTime);
        String fileName = Date + "ningxiang_sfs";
        String databaseNmae = " ningxiang_sfs";
        if (backup(hostIP, userName, password, savePath, fileName, databaseNmae) == false) {
            throw new ServiceException("备份数据库失败!");
        }else {
            System.out.println("备份数据库成功!");;
        }
    }

    /**
     * @param hostIP       ip地址,可以是本机也可以是远程
     * @param userName     数据库的用户名
     * @param password     数据库的密码
     * @param savePath     备份的路径
     * @param fileName     备份的文件名
     * @param databaseName 需要备份的数据库的名称
     * @return
     */
    public boolean backup(String hostIP, String userName, String password, String savePath, String fileName,
                          String databaseName) {
        fileName += ".sql";
        File saveFile = new File(savePath);
        if (!saveFile.exists()) {// 如果目录不存在
            saveFile.mkdirs();// 创建文件夹
        }
        if (!savePath.endsWith(File.separator)) {
            savePath = savePath + File.separator;
        }

        //拼接命令行的命令
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("C:\\mysqldump").append(" -h").append(hostIP).append(" -P3306");
        stringBuilder.append(" -u").append(userName).append(" -p").append(password).append(databaseName).append(">")
                .append(savePath).append(fileName);

        try {
            //调用外部执行exe文件的javaAPI
             System.out.println("cmd命令为:" + stringBuilder.toString());
             Runtime runtime = Runtime.getRuntime();

             System.out.println("开始备份:" + databaseName);
             Process process = runtime.exec("cmd /c " + stringBuilder.toString());
             System.out.println("备份成功!");
             process.waitFor();
             if (process.waitFor() == 0) {// 0 表示线程正常终止。
                 if(process != null){
                     process.getOutputStream().close();
                     return true;
                 }
             }
         } catch (InterruptedException e) {
             e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

}