bat文件:
@echo off
set errorlevel=0
set path_home_mysql="C:\Program Files\MySQL\MySQL Server 5.1\"
set path_bin_mysql=%path_home_mysql%bin\
set backup_dir="C:\backup\"
set backup_file=%backup_dir%backup_test.sql
set database_mysql=backup_test
set user_mysql=root
set password_mysql=1234
dir %backup_dir% || echo make dir &mkdir %backup_dir%
IF EXIST %backup_file% (del %backup_file% &echo %backup_file% is deleted)
echo backup mysql database:%database_mysql%
%path_bin_mysql%mysqldump.exe -u%user_mysql% -p%password_mysql% %database_mysql% > %backup_file%
echo end backup
备份:
Process ps = Runtime.getRuntime().exec("C:/backup_bat/backup.bat");
InputStream in = ps.getInputStream();
int c;
while ((c = in.read()) != -1) {
System.out.print(c);
}
in.close();
ps.waitFor();
还原:
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("C:\\Program Files\\MySQL\\MySQL Server 5.1\\bin\\mysql.exe -hlocalhost -uroot -p1234 --default-character-set=utf8 backup_test");
OutputStream outputStream = process.getOutputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("C:\\backup\\backup_test.sql"),"utf-8"));
String str = null;
StringBuffer sb = new StringBuffer();
while((str = br.readLine()) != null){
sb.append(str+"\r\n");
}
str = sb.toString();
System.out.println(str);
OutputStreamWriter writer = new OutputStreamWriter(outputStream,"utf-8");
writer.write(str);
writer.flush();
outputStream.close();
br.close();
writer.close();