备份MySQL数据库代码

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

/**
 *
 * 备份MySQL数据库(Windows)
 */
public class MysqlUtil {
    private static String mysqlIp = "127.0.0.1";// mysql主机ip
    private static String mysqlPort = "3306";//端口
    private static String userName = "root";//用户名
    private static String password = "123456";//密码
    private static String database = "vueblog";//数据库名
    private static String filePath = "D:\\oldDatabase";//存储文件夹

    private static final SimpleDateFormat yearMonthDayFormat = new SimpleDateFormat("yyyy-MM-dd");

    public static void statisticTasks() {
        String format = yearMonthDayFormat.format(new Date());
        //备份文件全路径
        if (!new File(filePath).exists()) {
            new File(filePath).mkdir();
        }
        String resultFile = filePath + File.separator + mysqlIp + "_" + database + "_" + format + ".sql";
        new File(resultFile).delete();
        try {
            String cmd = "mysqldump -h" + mysqlIp + " -P" + mysqlPort + " -u" + userName + " -p" + password + " --databases " + database + " > " + resultFile;
            //打印出命令,在CMD中运行一下看看是否报错
//            System.out.println("cmd:" + new String[]{"bash", "-c", cmd}.toString());
//            Process process = Runtime.getRuntime().exec(new String[]{"bash", "-c", cmd});
            System.out.println(cmd);
            Process process = Runtime.getRuntime().exec("cmd /c " + cmd);
            if (process == null) {
                System.err.println(process.getErrorStream());
                process.getErrorStream();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        statisticTasks();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值