import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimerTask;
public class Backup extends TimerTask{
private String user_name;
private String user_psw;
private String db_name;
private String host_ip;
private String user_charset;
private String backup_path;
private String stmt;
static SimpleDateFormat sdf =new SimpleDateFormat("yyyyMMddHHmmss");//完整的时间
public boolean BackupMysql(String user_name,String user_psw,String db_name,String host_ip,String user_charset,String backup_path){
this.user_name=user_name;
this.user_psw=user_psw;
this.db_name=db_name;
if(host_ip==null||host_ip.equals(""))
this.host_ip="localhost";
else
this.host_ip=host_ip;
if(user_charset==null||user_charset.equals(""))
this.user_charset=" ";
else
this.user_charset=" --default-character-set="+user_charset;
this.backup_path=backup_path;
this.stmt="C:\\Program Files\\MySQL\\MySQL Server 5.5\\bin\\mysqldump "+this.db_name+" -h "+this.host_ip+" -u"+this.user_name+" -p"+this.user_psw +this.user_charset+" --result-file="+this.backup_path;
boolean run_result=false;
try{
System.out.println("备份语句="+this.stmt);
Runtime.getRuntime().exec(this.stmt);
run_result=true;
System.out.println("------备份成功!-----");
}catch(Exception e){
e.printStackTrace();
}finally{
return run_result;
}
}
@Override
public void run() {
try{
System.out.println("数据库备份 --- 定时执行,开始时间为: " + new Date());
String path ="c:\\DataBaseBak"; //设置一个默认文件夹路径
File uploadFilePath = new File(path);
// 如果该目录不存在,则创建之
if(uploadFilePath.exists() == false) {
uploadFilePath.mkdirs();
System.out.println("路径不存在,但是已经成功创建了" + path);
}else{
System.out.println("文件路径存在" + path);
}
String time=sdf.format(new Date());
System.out.println("---"+time);
BackupMysql("root","sasa","jforum","10.5.1.103","utf8",path+"\\jforum"+time+".sql");
System.out.println(" 数据库备份 --- 定时执行,结束时间为: " + new Date());
}catch (Exception e) {
}
}
}