首页 > 数据库技术 > 详细

数据库备份

时间:2020-02-28 16:16:23      阅读:54      评论:0      收藏:0      [点我收藏+]
import java.io.File;
import java.util.Date;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import com.ibm.icu.text.SimpleDateFormat;
@Configuration      //1.主要用于标记配置类,兼备Component的效果。
@EnableScheduling
public class MysqlUtil {
    @Value("${spring.datasource.ip}")
    private String mysqlIp;// mysql主机ip
    @Value("${spring.datasource.port}")
    private String mysqlPort;//端口
    @Value("${spring.datasource.username}")
    private String userName;//用户名
    @Value("${spring.datasource.password}")
    private String password;//密码
    @Value("${spring.datasource.dataname}")
    private String database;//数据库名
    @Value("${spring.datasource.filepath}")
    private String filePath;

    private static final SimpleDateFormat yearMonthDayFormat = new SimpleDateFormat("yyyy-MM-dd");
    @Scheduled(cron="0/20 * * * * ?")
    public void statisticTasks() {
        //备份文件全路径
                //String dateString = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
                if(!new File(filePath).exists()){
                    new File(filePath).mkdir();
                }
                String resultFile =filePath+ File.separator + mysqlIp +"_"+ database +".sql";
                new File(resultFile).delete();
                try {
                    String cmd =  "docker exec -it mysql mysqldump -h"+mysqlIp+" -P"+mysqlPort+" -u"+ userName +" -p"+password+" "+database + ">" +
                            resultFile;
                    System.out.println("cmd:"+new String[]{"bash", "-c",cmd}.toString());  
                    Process process=Runtime.getRuntime().exec(new String[]{"bash", "-c",cmd});
                    if(process==null){
                        System.err.println(process.getErrorStream());
                        process.getErrorStream();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
     }

}

数据库:mysql 位置:docker 容器 所以增加 docker exec -it mysql 因为可能是远程数据库:所以增加 -h 和-P 用于标识 地址和端口号
直接执行Runtime.getRuntime.exec(cmd)时 一直不能生成sql语句,也不报错,但是在linux远程界面上直接执行可以生成sql语句,
所以应该是在程序中执行的语句有问题。
一开始以为是权限问题,更改了文件夹的权限还是生成不了。
百度说是cmd中存在空格的问题,后面执行了cmd.replaceAll(" ","\" \"")在执行就直接报错了 遂放弃
后面说加上"bash" "-c"并用字符串数组的形式进行执行 果然生成了sql,和权限没有关系,
百度了 bash -c 意思是执行命令时用 bash shell来执行命令,可能是linux系统没有默认或者怎样吧。
bash是shell的一种 shell是充当人与计算机之间的翻译官,用来把命令翻译成计算机识别的二进制文件。
一开始没有生成sql可能是cmd中存在空格等字符,空格在linux系统有特殊含义,所以解析成不是计算机可以识别的命令吧。故而没有生成sql语句。

数据库备份

原文:https://www.cnblogs.com/xiatc/p/12376952.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!