编写bat文件
@echo off
set "date_string=%date:~0,4%-%date:~5,2%-%date:~8,2%"
set "time_string=%time:~0,2%-%time:~3,2%-%time:~6,2%"
echo "==========开始备份数据库============"
set back_path=c:\xym\xymsql
if not exist %back_path% md %back_path%
set database=xym
set username=root
set password=root
set mysql=C:\"Program Files"\MySQL\"MySQL Server 5.5"\bin\mysqldump.exe
set "file_string=%back_path%\data_%date_string%-%time_string%"
set "filepath=%file_string%-xym.sql"
echo %filepath%
%mysql% -u%username% -p%password% xym > "%filepath%"
echo "==========数据库备份成功============"
java代码:
package com.sm; import java.io.IOException; public class CmdMain {
public static void Backup() { // 执行批处理文件
String strcmd = "cmd.exe /c start c:\\xym\\xymsql\\sqldum.bat";
// String strcmd1 = "cmd.exe /c start c:\\test.bat";
Runtime rt = Runtime.getRuntime();
Process ps = null;
try {
ps = rt.exec(strcmd);
} catch (IOException e1) {
e1.printStackTrace();
}
try {
ps.waitFor();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int i = ps.exitValue();
if (i == ) {
System.out.println("执行完成.");
} else {
System.out.println("执行失败.");
}
ps.destroy();
ps = null; // 批处理执行完后,根据cmd.exe进程名称
// kill掉cmd窗口
new CmdMain().killProcess(); } public void killProcess() {
Runtime rt = Runtime.getRuntime();
Process p = null;
try {
rt.exec("cmd.exe /C start wmic process where name='cmd.exe' call terminate");
} catch (IOException e) {
e.printStackTrace();
}
}
}