JAVA实现数据库备份

JAVA实现数据库备份

package com.platform.controller;

import com.platform.utils.R;
import org.springframework.web.bind.annotation.*;

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

import javax.servlet.http.HttpServletRequest;

/**
 * Controller
 *
 * @author lwq
 * @email [email protected]
 * @date 2019-12-23 09:37:35
 */
@RestController
@RequestMapping("dbBackup")
public class DbBackupController {
	private static String separator = "/";
  
    /**
     * 备份数据库
     */
    @RequestMapping("/db")
    public R list(HttpServletRequest request) {
    	try {
    		String realPath = request.getServletContext().getRealPath("/");
        	String path = realPath + "/dbBackUp/" + separator;
        	String sqlFileName = getRunTimeName();
			dbBackUp("Mysql的用户名", "Mysql的密码", "要备份的数据库名", "要保存的路径", '备份的数据名,此处用时间戳取名了');
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("备份数据失败");
		}
        return R.ok();
    }    
    /**
     * 
     * @param root 用户名
     * @param pwd 密码
     * @param dbName 数据库名
     * @param backPath 保存路径
     * @param backName 保存名称
     * @throws Exception
     */
    public static void dbBackUp(String root,String pwd,String dbName,String backPath,String backName) throws Exception {
        String pathSql = backPath+backName;
        File fileSql = new File(pathSql);
        File file = new File(backPath);
        //创建备份sql文件
        file.mkdirs();
        if (!fileSql.exists()){
            fileSql.createNewFile();
        }
        //mysqldump -hlocalhost -uroot -p123456 db > /home/back.sql
        StringBuffer sb = new StringBuffer();
        sb.append("mysqldump");
        sb.append(" -h 127.0.0.1");//此处ip可以是别的机器的ip
        sb.append(" -u"+root);
        sb.append(" -p"+pwd);
        sb.append(" "+dbName+" >");
        sb.append(pathSql);
        System.out.println("cmd命令为:"+sb.toString());
        Runtime runtime = Runtime.getRuntime();
        System.out.println("开始备份:"+dbName);
        System.out.println("cmd /c"+sb.toString());
        Process process = runtime.exec("cmd /c"+sb.toString());
        System.out.println("备份成功!");
    } 
    public static String getRunTimeName() {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate=sdf.format(new Date());
        String result="";
        Random random=new Random();
        for(int i=0;i<3;i++){
            result+=random.nextInt(10);
        }
        return newDate+result+".sql";
    }
}

你可能感兴趣的:(数据库,项目)