栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

数据库的还原与备份 java mysql

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

数据库的还原与备份 java mysql

java备份mysql数据库
package com.lear.util;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

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


@Component
public class DbJob {
    private final Log logger = LogFactory.getLog(DbJob.class);

    @Scheduled(cron = "58 05 19 * * ?")
    public void back(){
        System.out.println("现在时间是"+new Date());
        Runtime runtime = Runtime.getRuntime();  //获取Runtime实例
        String user = "root";
        String password = "root";
        String database = "mydb"; // 需要备份的数据库名
        Date currentDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
        String sdfDate = sdf.format(currentDate);
        String filepath = "d:\database_copy\time_" + sdfDate + ".sql"; // 备份的路径地址
        //执行命令
        String stmt = "mysqldump --column-statistics=0 -h 127.0.0.1 -u "+user+" -p"+password+" --databases "+database+" > "+filepath;
        System.out.println(stmt);
        try {
            String[] command = { "cmd", "/c", stmt};
            Process process = runtime.exec(command);
            InputStream input = process.getInputStream();
            System.out.println(IOUtils.toString(input, "UTF-8"));
            //若有错误信息则输出
            InputStream errorStream = process.getErrorStream();
            System.out.println(IOUtils.toString(errorStream, "UTF-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
java还原mysql数据库
    @Scheduled(cron = "00 40 20 * * ?")
    
    public static boolean importDatabase() {

        String hostIP="127.0.0.1";
        String hostPort="3306";
        String userName="root";
        String password="root";
        String importFilePath="D:\database_copy\";
        String sqlFileName="time_2022-03-13_19-05-58.sql";
        String databaseName="mydb";

        File imporFile = new File(importFilePath);
        if (!imporFile.exists()) {
            imporFile.mkdirs();
        }

        if (!importFilePath.endsWith(File.separator)) {
            importFilePath = importFilePath + File.separator;
        }

        //mysql -h127.0.0.1 -uroot -P3306 -p test
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/763919.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号