java 备份数据库

  1. MYSQL备份命令行: 
  2. SQL代码  mysqldump -hhostname -uusername -ppassword databasename > ‘backupfile’    
  3. JAVA代码如下: Java代码 
  4. public final String BACKUP_COMMAND ="mysqldump";    
  5. public final String ENCODING ="utf8";
  6. public boolean backup(String file) {
  7. boolean isSuccess =true; 
  8. try {
  9. Runtime rt = Runtime.getRuntime();
  10. String backupStr =this.getBackupStr();
  11. logger.infoT(backupStr);        
  12. Process process = rt.exec(backupStr);
  13. BufferedReader br =new BufferedReader(new InputStreamReader(process.getInputStream(), ENCODING));
  14. String inStr ="";
  15. StringBuffer sb =new StringBuffer("");         
  16. while ((inStr = br.readLine()) !=null) {              
  17. sb.append(inStr).append("");    
  18. }
  19. String outStr = sb.toString();          
  20. OutputStreamWriter writer =new OutputStreamWriter(new FileOutputStream(file), ENCODING);     
  21. writer.write(outStr);       
  22. writer.flush();          
  23. br.close();           
  24. writer.close();     
  25. }catch (Exception e) {   
  26. e.printStackTrace();         
  27. isSuccess =false;      
  28. }
  29. return isSuccess;




mysql   -hhostname -uusername -ppassword databasename < ‘backupfile’    
JAVA代码如下: Java代码 53 
public final String REVERT_COMMAND ="mysql";    54    55 
public boolean revert(String file) {    56     
try {    57          
Runtime rt = Runtime.getRuntime();    58          
String revertStr =this.getRevertStr();    59          
Process process = rt.exec(revertStr);    60    61          
String inStr;    62          
StringBuffer sb =new StringBuffer("");    63          
BufferedReader br =new BufferedReader(new InputStreamReader(    64         
new FileInputStream(file), ENCODING));    65         
while ((inStr = br.readLine()) !=null) {    66              
sb.append(inStr).append("");    67          
}    68          
String outStr = sb.toString();    69    70          
OutputStreamWriter writer =new OutputStreamWriter(process.getOutputStream(), ENCODING);    71         
writer.write(outStr);    72          
writer.flush();    73          
br.close();    74          
writer.close();    75      
}catch (Exception e) {    76          
e.printStackTrace();    77        
return false;    78     
}    79     
return true;    80 
}    81    82 
private String getRevertStr() {    83      
String backupStr = REVERT_COMMAND +" -u" + db.getUserName() +" -p" + db.getPassword() +" -h" + db.getHost() +" " + db.getName();
return backupStr;    85 
 } 

猜你喜欢

转载自ruanqiangbeyond201208043532.iteye.com/blog/1731411