linux和windows上备份Mysql数据库java代码

以下为实现在windows和linux 上备份Mysql数据库的java代码,它通过动态判断操作体统和动态从链接数据库的

配置文件(本文是用hibernat的配置文件)读出数据库信息生成可执行脚本,再使用java调用此脚本而实现数据

库的备份和恢复,当然你可以根据自己的需要修改扩展,呵呵

/*
 *  
 * TODO 要更改此生成的文件的模板,请转至
 * 窗口 - 首选项 - Java - 代码样式 - 代码模板
 */
package com.et.yizh.zhp.data;

import javax.servlet.http.HttpServletRequest;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.*;

import com.et.buss.login.Account;
import com.et.util.Log;
import com.et.util.StrUtil;

/**
 * @author zhangpeng
 *
 * TODO 要更改此生成的类型注释的模板,请转至
 * 窗口 - 首选项 - Java - 代码样式 - 代码模板
 */
public class DatabaseManager {
  
 private String message="";
 private String operateFlag="";
 private Hashtable pageInfo=new Hashtable();
 private Account objAccount=null;
 private String db_tools_path = "";  //执行文件保存路径
 private String db_backup_path= ""; //备份文件保存路径
 private HttpServletRequest request;
 //private ServletContext application;

 //构造及初始化
 public DatabaseManager(HttpServletRequest request){
  this.request=request;
  //this.application=application; 
  this.objAccount=(Account)request.getSession().getAttribute(Account.ACCOUNT_KEY);
  this.db_backup_path= DataFile.getFilepath();  //执行文件保存路径
  this.db_tools_path= DataFile.getBinpath();  //备份文件保存路径
 }
 //构造及初始化
 public DatabaseManager(){

 }
 //获取错误信息
 public String getMessage(){  
  return message; 
 }    
    /**
     * 进行数据备份
     */
 public int backup(){ 
  if(this.objAccount==null){
   message="对不起!请先登录,才能做此操作!";  
   return -1; 
  } 
  boolean flag=true;
  //初始化环境
  String new_id=StrUtil.generalSrid();
  String fileName=new_id+".sql";
  //初始化参数及文件校验
  
  File data_file=new File(db_backup_path,fileName);//备份脚本文件对象
  
  String binname = this.getBackBin(); //获得执行备份的文件名
  
  File bin_file=new File(db_tools_path,binname); //执行文件对象
  
  String para=this.getCommandParameter(); 
  
  String writeMsg = bin_file.getAbsolutePath()+para+" > "+data_file.getAbsoluteFile();
  
  File bat_file=this.writeMsgToFile(writeMsg);   //执行命令的脚本文件
  flag=(bin_file.exists()&&bat_file.exists());   //文件校验如果都存在为真
  if(!flag){
   message="备份数据库失败!提示:未找到相应的文件!";  
   return -1;  
  }  
  //执行备份过程
  CmdUtil cmd=new CmdUtil();
  try{
   cmd.excute(this.getShell()+bat_file.getAbsolutePath());//执行命令脚本
   int i = cmd.waitFor(); //进程退出结果
   //Process process = Runtime.getRuntime().exec(bat_file.getAbsolutePath());//执行命令脚本
   //int i = process.waitFor();

   cmd.kill();//杀死进程
   Log.write("====backup===result======"+i);
   if(i!=0){
    message="备份数据库失败!可能原因:服务器繁忙!请稍后重试!";
    this.delFile(data_file);//非正常退出而失败时,删除已经生成的不完整文件
    return -1;  
   }
  }catch(Exception e){
   this.delFile(data_file);//非正常退出而失败时,删除已经生成的不完整文件
   message = "备份数据库失败!可能原因:服务器繁忙!请稍后重试!!";
   Log.write(e.getMessage());
   return -1;
  }
  return 1;
  
 }
 /**
  * 进行数据恢复
  */
 public int restore(){ 
  if(this.objAccount==null){
   message="对不起!请先登录,才能做此操作!";  
   return -1; 
  } 
  boolean flag=true;
  //初始化环境
  String fileName=request.getParameter("id");
  if(fileName.indexOf(".sql")==-1){    //不是sql脚本文件
   message="数据库恢复失败!提示:数据脚本文件格式不正确!";
   return -1; 
  }
  //初始化参数及文件校验
  File data_file=new File(db_backup_path,fileName);//备份脚本文件对象
  
  String binname = this.getRestoreBin(); //获得执行恢复的文件名
  
  File bin_file = new File(db_tools_path,binname); //执行文件对象
  
  String para = this.getCommandParameter(); 
  
  File bat_file=this.writeMsgToFile(bin_file.getAbsolutePath()+para+" < "+data_file.getAbsoluteFile());
  
  flag=(data_file.exists()&&bin_file.exists()&&bat_file.exists());   //文件校验
  if(!flag){
   message="恢复数据库失败!提示:未找到相应的文件!";
   return -1;  
  }  
  //执行恢复过程
  CmdUtil cmd=new CmdUtil();
  try{
   cmd.excute(this.getShell()+bat_file.getAbsolutePath());//执行命令脚本
   int i = cmd.waitFor(); //进程等待 返回退出结果

   cmd.kill();//杀死进程

   Log.write("=====restore==result======"+i);
   if(i!=0){
    message="恢复数据库失败!可能原因:服务器繁忙!请稍后重试!";
    return -1;  
   }
  }catch(Exception e){
   message = "恢复数据库失败!可能原因:服务器繁忙!请稍后重试!!";
   Log.write(e.getMessage());
   return -1;
  }     
  return 1;
 }  
 
  //删除文件
 public void delFile(File file){
  if(file.exists()){
   file.delete();//删除文件
  }
 }
   /**
 * 判断操作系统,给出相应执行脚本
 */
 public String getShell(){
  return DataFile.isLinux()?"/bin/sh ":""; 
 }
   /**
 * 判断操作系统,使用相应的备份执行文件
 */
 public String getBackBin(){
  return DataFile.isLinux()?"mysqldump":"mysqldump.exe"; 
 }
   /**
 * 判断操作系统,使用相应的恢复执行文件
 */
 public String getRestoreBin(){
  return DataFile.isLinux()?"mysql":"mysql.exe"; 
 } 
  /**
 * 从hibernate中获取备份和恢复的参数
 */ 
 private String getCommandParameter(){
  net.sf.hibernate.cfg.Configuration cfg=new net.sf.hibernate.cfg.Configuration();
  try{
   cfg.configure("/hibernate.cfg.xml");       
  }catch (Exception e) {
   Log.write("%%%%====解析/hibernate.cfg.xml失败!! Error Creating SessionFactory %%%%");
   Log.write(e.getMessage());
  } 
  
  String url=cfg.getProperty("connection.url");
  String s=url.replaceAll("jdbc:mysql://","");
  s=s.replaceAll("/",":"); 

  String pare[]=s.split(":");
  
  StringBuffer sb=new StringBuffer(""); 
  
  //2获得备份或恢复的参数
  String host=pare[0];
  String port=pare[1];
  String user=cfg.getProperty("connection.username");;
  String passwd=cfg.getProperty("connection.password");
  String database=pare[2];     
  
   sb.append("  -h"+host);
   sb.append("  -P"+port);  
   sb.append("  -u"+user);        
   sb.append("  -p"+passwd);
  // sb.append(" --skip-comments -q ");//不要注释 只能在备份时用
   sb.append("  -B "+database); //存储多个数据库 

  return sb.toString();  
 }
   /**
 *   写一段字符串到执行文件中
 */
 private File writeMsgToFile(String msg){
  String shellfile = DataFile.isLinux()?"temp.txt":"temp.bat";//根据操作系统
  File bat_file=new File(db_tools_path,shellfile);
  if(bat_file.exists()){
   bat_file.delete();
  }  
  try{   
   BufferedWriter out=new BufferedWriter(new FileWriter(bat_file)); 
   out.write(msg); 
   out.close();
  }catch(Exception e){
   bat_file.delete();
   return null;  
  }
  return bat_file;   
 }

}
下面是上面类中用的CmdUtil类:

/**
 * 创建日期 2007-01-26
 *
 */
package com.et.yizh.zhp.data;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import com.et.util.Log;

/**
 * @author zhangpeng
 * 
 */
public class CmdUtil {
 private Process p = null;

 /**
  * @return
  */
 public InputStream getErrorStream() {
  return p.getErrorStream();
 }

 /**
  * @return
  */
 public InputStream getInputStream() {
  return p.getInputStream();
 }

 /**
  * @return
  */
 public OutputStream getOutputStream() {
  return p.getOutputStream();
 }

 /**
  * 清除运行外部命令的线程
  * 
  */
 public final void kill() {
  if (p != null) {
   p.destroy();
  }
  p = null;
 }

 /**
  * 
  */
 public void destroy() {
  p.destroy();
 }

 /**
  * @return
  */
 public int exitValue() {
  return p.exitValue();
 }
 /**
  * @return
  */
 public int waitFor() {
  try {
   return  p.waitFor();
  } catch (InterruptedException e) {
   // TODO 自动生成 catch 块
   e.printStackTrace();
   return -1;
  }
 }

 /**
  * 执行一个外部命令
  *
  * @param shellCmd
  * @return
  */
 public final boolean excute(String shellCmd) {
  try {
   if (p != null) {
    kill();
   }
   Runtime run = Runtime.getRuntime();
   p = run.exec(shellCmd);

  } catch (Exception e) {
   Log.write(e.getMessage());
   return false;
  }
  return true;
 }

 public final StringBuffer cmd(String shellCmd, boolean isGetCmdOutPut) {
  this.excute(shellCmd);
  if (!isGetCmdOutPut)
   return null;
  StringBuffer sb = new StringBuffer(2048);
  try {
   //InputStream error=p.getErrorStream();
   //OutputStream out = p.getOutputStream();
   DataInputStream in = new DataInputStream(p.getInputStream());
   BufferedReader reader = new BufferedReader(
     new InputStreamReader(in));
   String line;
   do {
    line = reader.readLine();
    if (line == null) {
     break;
    } else {
     System.out.println(line);
     sb.append(line);
     sb.append("\n");
    }
   } while (true);
   reader.close();

  } catch (Exception e) {
   return null;
  }
  return sb;
 }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值