Java web 项目中对数据库备份和恢复

说白了,还是去调用cmd实现数据库的备份和还原功能。

备份:

mysqldump -hserverUrl -uusername -ppassword dbname > savePath

还原:

mysql -hserverUrl -uusername -ppassword dbname < filePath

Java web 项目中对数据库备份和恢复_第1张图片

Java web 项目中对数据库备份和恢复_第2张图片

package com.cxx.backupdb;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author: cxx
 * 数据库备份与还原
 * @Date: 2018/4/28 19:56
 */
public class DbOperate {

    /**
     * 备份数据库db
     * @param root
     * @param pwd
     * @param dbName
     * @param backPath
     * @param backName
     */
    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);
        //创建备份sql文件
        if (!fileSql.exists()){
            fileSql.createNewFile();
        }
        //mysqldump -hlocalhost -uroot -p123456 db > /home/back.sql
        StringBuffer sb = new StringBuffer();
        sb.append("mysqldump");
        sb.append(" -h60.115.212.196");
        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);
        Process process = runtime.exec("cmd /c"+sb.toString());
        System.out.println("备份成功!");
    }

    /**
     * 恢复数据库
     * @param root
     * @param pwd
     * @param dbName
     * @param filePath
     * mysql -hlocalhost -uroot -p123456 db < /home/back.sql
     */
    public static void dbRestore(String root,String pwd,String dbName,String filePath){
        StringBuilder sb = new StringBuilder();
        sb.append("mysql");
        sb.append(" -h60.115.212.196");
        sb.append(" -u"+root);
        sb.append(" -p"+pwd);
        sb.append(" "+dbName+" <");
        sb.append(filePath);
        System.out.println("cmd命令为:"+sb.toString());
        Runtime runtime = Runtime.getRuntime();
        System.out.println("开始还原数据");
        try {
            Process process = runtime.exec("cmd /c"+sb.toString());
            InputStream is = process.getInputStream();
            BufferedReader bf = new BufferedReader(new InputStreamReader(is,"utf8"));
            String line = null;
            while ((line=bf.readLine())!=null){
                System.out.println(line);
            }
            is.close();
            bf.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("还原成功!");
    }



    public static void main(String[] args) throws Exception {
        String backName = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date())+".sql";
        DbOperate.dbBackUp("root","123456","ks","F:/",backName);
        dbRestore("root","123456","ks","F://2018-04-30-19-28-28.sql");
    }

}

你可能感兴趣的:(后端编程)