J2EE下的oracle数据库备份方法

简介:

 

1./**
  *   @Description :   实现数据库的备份
*   @since JDK1.5
  *   @date   (开发日期):   2009 - 06 - 10
  *   @ 注意事项 :数据库备份文件放在服务器上 , 路径在 Constant 里设置,如希望正确使用,需要导入相关 jar
  *    
  */
 
 
     public class  BackUpDataBaseAction  extends  Action {
 
    static  Logger logger = Logger.getLogger(BackUpDataBaseAction. class);
 
    public  ActionForward execute(ActionMapping actionMapping,
           ActionForm actionForm, HttpServletRequest httpServletRequest,
           HttpServletResponse httpServletResponse) {
 
       Calendar cDay = Calendar.getInstance();
       SimpleDateFormat myf =  new  SimpleDateFormat( "yyyyMMddHHmmss" );
       String day = myf.format(cDay.getTime());
        //  获得 Constant 中定义的数据库备份文件存放路径,格式如:
         // public static final String DataBaseBackUpPath = "D:\\sOADB\\";
String outputFile = Constant.DataBaseBackUpPath;
        //  如果服务器端硬盘上不存在 outputFile 目录,则创建这个目录
       File mydir =  new  File(outputFile);
        if  (!(mydir.exists())) {
           mydir.mkdir();
       }
 
        //  备份文件名
       String fileName =  "soa"  + day +  ".dmp" ;
        //  将备份好的数据库文件放在服务器端的 outputFile 目录下
      
        //  得到数据库的连接信息
 
         //  得到物理路径 , 取得 applicationContext.xml 中数据库定义,
// url,usrname,password O/R 映射文件等内容
       ServletContext m_application =  this .getServlet().getServletContext();
       String path = m_application.getRealPath( "/" );
       String filename = path +  "WEB-INF\\applicationContext.xml" ;
       WriteXMLWithDom wxf =  new  WriteXMLWithDom();
       String[] str = wxf.GetOralAddrWithDom(filename);
        if  (str[0].equalsIgnoreCase( "" )) {
            return  actionMapping.findForward( "failure" );
       }
        // str[1]  用户名   ,[2]  用户密码  ,
        //  服务器地址 ,[0]
       String command =  "exp  " +str[1]+ "/" +str[2]+ "@" +str[0].substring(str[0].lastIndexOf( ':' )+1)+ " file="  + outputFile+ fileName;
       Runtime rt = Runtime.getRuntime();
        // Process process=null;
        try  {
 
            // process=rt.exec(command);
           rt.exec(command);
            // process.waitFor();
            //  假等待一下 , 目的是让其能在文件列表中列出 , 可以 process.destroy() 得到
           Thread.sleep(5000);
        catch  (Exception e) {
             // 捕捉异常
           String errorSORT = Constant.errorBeifen;
           httpServletRequest.setAttribute( "ERRORSORT" , errorSORT);
          
           String error =  " 数据库备份操作失败,请稍候再试!  " ;
           httpServletRequest.setAttribute( "PUBLICINFERROR" , error);
            return  actionMapping.findForward( "warning" );
       }
        // p.destroy();
        logger .warn(StringUtil.getLogString(((UserInfo) httpServletRequest
              .getSession().getAttribute(Constant.USER)).getUserAccount(),
               " 执行了数据库备份操作 " ));
 
        return  actionMapping.findForward( "success" );
    }
 
}
 2.获取application中关于数据库定义的信息,包括用户名,密码,url,.hbm.xml文件等。
package com.gao.sys;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;
public class WriteXMLWithDom {
 public WriteXMLWithDom() {
 }
 public int CallWriteXMLWithDom(String fname, String tablename) {
  int returnValue = 0;
  try {
   File file = new File(fname);
   BufferedInputStream bufferedInputStream = new BufferedInputStream(
     new FileInputStream(file));
   DocumentBuilderFactory factory = DocumentBuilderFactory
     .newInstance();
   DocumentBuilder parser = factory.newDocumentBuilder();
   InputStream instr = new FileInputStream(fname);
   Document doc = parser.parse(instr);
   // 根节点
   NodeList nodeList = doc.getElementsByTagName("beans");
   for (int b = 0; b < nodeList.getLength(); b++) {
    Node book = nodeList.item(b);
    for (Node bean = book.getFirstChild(); bean != null; bean = bean
      .getNextSibling()) {
     // bean节点
     if (bean.getNodeName().equals("bean")) {
      for (int i = 0; i < bean.getChildNodes().getLength(); i++) {
       // property节点
       Node pro = bean.getChildNodes().item(i);
       if (pro.getAttributes() != null
         && pro.getAttributes().getNamedItem("name") != null) {
        if (pro.getAttributes().getNamedItem("name")
          .getNodeValue().equals(
            "mappingResources")) {
         // list节点
         Node listn = pro.getFirstChild()
           .getNextSibling();
         Element elistn = (Element) listn;
         Element newvalue = doc
           .createElement("value");
         Text newtest = doc
           .createTextNode("com/gao/data/bean/"
             + tablename + ".hbm.xml");
         newvalue.appendChild(newtest);
         elistn.appendChild(newvalue);
        }
       }
      }
     }
    }
   }
   // }
   FileOutputStream outStream = new FileOutputStream(fname);
   OutputStreamWriter outWriter = new OutputStreamWriter(outStream,
     "UTF-8");
   try {
    // Prepare the DOM document for writing
    Source source = new DOMSource(doc);
    // Prepare the output file
    Result result = new StreamResult(outWriter);
    // Write the DOM document to the file
    Transformer xformer = TransformerFactory.newInstance()
      .newTransformer();
    xformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    // xformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"dtd/spring-beans.dtd");
    // xformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC,"-//SPRING//DTD
    // BEAN//EN");
    xformer.transform(source, result);
   } catch (TransformerConfigurationException e) {
    e.printStackTrace();
   } catch (TransformerException e) {
    e.printStackTrace();
   }
   try {
    outWriter.close();
    outStream.close();
    returnValue = 1;
   } catch (IOException e) {
    // TODO 自动生成 catch 块
    e.printStackTrace();
   } finally {
    return returnValue;
   }
  } catch (ParserConfigurationException e) {
   e.printStackTrace();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (SAXException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   return returnValue;
  }
 }
 public int DeleteNodeFromXMLWithDom(String fname, String tablename) {
  int returnValue = 0;
  try {
   File file = new File(fname);
   BufferedInputStream bufferedInputStream = new BufferedInputStream(
     new FileInputStream(file));
   DocumentBuilderFactory factory = DocumentBuilderFactory
     .newInstance();
   DocumentBuilder parser = factory.newDocumentBuilder();
   InputStream instr = new FileInputStream(fname);
   Document doc = parser.parse(instr);
   // 根节点
   NodeList nodeList = doc.getElementsByTagName("beans");
   for (int b = 0; b < nodeList.getLength(); b++) {
    Node book = nodeList.item(b);
    for (Node bean = book.getFirstChild(); bean != null; bean = bean
      .getNextSibling()) {
     // bean节点
     if (bean.getNodeName().equals("bean")) {
      for (int i = 0; i < bean.getChildNodes().getLength(); i++) {
       // property节点
       Node pro = bean.getChildNodes().item(i);
       if (pro.getAttributes() != null
         && pro.getAttributes().getNamedItem("name") != null) {
        if (pro.getAttributes().getNamedItem("name")
          .getNodeValue().equals(
            "mappingResources")) {
         // list节点
         Node listn = pro.getFirstChild()
           .getNextSibling();
         Element elistn = (Element) listn;
         
         Node valuen = elistn.getFirstChild();
         
         int k = valuen.getChildNodes().getLength();
         for(int j=0;j<elistn.getChildNodes().getLength()-1;j++){
          valuen=valuen.getNextSibling();
          if(valuen.getTextContent().contains(
            tablename)){
           listn.removeChild(valuen);
           break;
          }
          
          
         }
        
        }
       }
      }
     }
    }
   }
   // }
   FileOutputStream outStream = new FileOutputStream(fname);
   OutputStreamWriter outWriter = new OutputStreamWriter(outStream,
     "UTF-8");
   try {
    // Prepare the DOM document for writing
    Source source = new DOMSource(doc);
    // Prepare the output file
    Result result = new StreamResult(outWriter);
    // Write the DOM document to the file
    Transformer xformer = TransformerFactory.newInstance()
      .newTransformer();
    xformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    xformer.transform(source, result);
   } catch (TransformerConfigurationException e) {
    e.printStackTrace();
   } catch (TransformerException e) {
    e.printStackTrace();
   }
   try {
    outWriter.close();
    outStream.close();
    returnValue = 1;
   } catch (IOException e) {
    // TODO 自动生成 catch 块
    e.printStackTrace();
   } finally {
    return returnValue;
   }
  } catch (ParserConfigurationException e) {
   e.printStackTrace();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (SAXException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   return returnValue;
  }
 }
 public String[] GetOralAddrWithDom(String fname) {
  String[] str = { "", "", "" };
  try {
   File file = new File(fname);
   BufferedInputStream bufferedInputStream = new BufferedInputStream(
     new FileInputStream(file));
   DocumentBuilderFactory factory = DocumentBuilderFactory
     .newInstance();
   DocumentBuilder parser = factory.newDocumentBuilder();
   InputStream instr = new FileInputStream(fname);
   Document doc = parser.parse(instr);
   // 根节点
   NodeList nodeList = doc.getElementsByTagName("beans");
   for (int b = 0; b < nodeList.getLength(); b++) {
    Node book = nodeList.item(b);
    for (Node bean = book.getFirstChild(); bean != null; bean = bean
      .getNextSibling()) {
     // bean节点
     if (bean.getNodeName().equals("bean")
       && bean.getAttributes().getNamedItem("id")
         .getNodeValue().equals("DataSource")) {
      for (int i = 0; i < bean.getChildNodes().getLength(); i++) {
       // property节点
       Node pro = bean.getChildNodes().item(i);
       if (pro.getAttributes() != null
         && pro.getAttributes().getNamedItem("name") != null) {
        if (pro.getAttributes().getNamedItem("name")
          .getNodeValue().equals("url")) {
         str[0] = pro.getAttributes().getNamedItem(
           "value").getNodeValue();
        }
        if (pro.getAttributes().getNamedItem("name")
          .getNodeValue().equals("username")) {
         str[1] = pro.getAttributes().getNamedItem(
           "value").getNodeValue();
        }
        if (pro.getAttributes().getNamedItem("name")
          .getNodeValue().equals("password")) {
         str[2] = pro.getAttributes().getNamedItem(
           "value").getNodeValue();
        }
       }
      }
     }
    }
   }
  } catch (ParserConfigurationException e) {
   e.printStackTrace();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (SAXException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   return str;
  }
 }
}
 
大家可以比较阅读的文章;
 
 
      本文转自 gaochaojs 51CTO博客,原文链接:http://blog.51cto.com/jncumter/166362,如需转载请自行联系原作者


相关文章
|
7月前
|
Oracle 关系型数据库 Linux
【赵渝强老师】Oracle数据库配置助手:DBCA
Oracle数据库配置助手(DBCA)是用于创建和配置Oracle数据库的工具,支持图形界面和静默执行模式。本文介绍了使用DBCA在Linux环境下创建数据库的完整步骤,包括选择数据库操作类型、配置存储与网络选项、设置管理密码等,并提供了界面截图与视频讲解,帮助用户快速掌握数据库创建流程。
609 93
|
6月前
|
Oracle 关系型数据库 Linux
【赵渝强老师】使用NetManager创建Oracle数据库的监听器
Oracle NetManager是数据库网络配置工具,用于创建监听器、配置服务命名与网络连接,支持多数据库共享监听,确保客户端与服务器通信顺畅。
337 0
|
9月前
|
存储 Oracle 关系型数据库
服务器数据恢复—光纤存储上oracle数据库数据恢复案例
一台光纤服务器存储上有16块FC硬盘,上层部署了Oracle数据库。服务器存储前面板2个硬盘指示灯显示异常,存储映射到linux操作系统上的卷挂载不上,业务中断。 通过storage manager查看存储状态,发现逻辑卷状态失败。再查看物理磁盘状态,发现其中一块盘报告“警告”,硬盘指示灯显示异常的2块盘报告“失败”。 将当前存储的完整日志状态备份下来,解析备份出来的存储日志并获得了关于逻辑卷结构的部分信息。
|
7月前
|
SQL Oracle 关系型数据库
Oracle数据库创建表空间和索引的SQL语法示例
以上SQL语法提供了一种标准方式去组织Oracle数据库内部结构,并且通过合理使用可以显著改善查询速度及整体性能。需要注意,在实际应用过程当中应该根据具体业务需求、系统资源状况以及预期目标去合理规划并调整参数设置以达到最佳效果。
470 8
|
8月前
|
存储 关系型数据库 MySQL
MySQL数据库中进行日期比较的多种方法介绍。
以上方法提供了灵活多样地处理和对比MySQL数据库中存储地不同格式地日子信息方式。根据实际需求选择适当方式能够有效执行所需操作并保证性能优化。
743 10
|
9月前
|
SQL Oracle 关系型数据库
比较MySQL和Oracle数据库系统,特别是在进行分页查询的方法上的不同
两者的性能差异将取决于数据量大小、索引优化、查询设计以及具体版本的数据库服务器。考虑硬件资源、数据库设计和具体需求对于实现优化的分页查询至关重要。开发者和数据库管理员需要根据自身使用的具体数据库系统版本和环境,选择最合适的分页机制,并进行必要的性能调优来满足应用需求。
422 11
|
9月前
|
Oracle 关系型数据库 数据库
数据库数据恢复—服务器异常断电导致Oracle数据库报错的数据恢复案例
Oracle数据库故障: 某公司一台服务器上部署Oracle数据库。服务器意外断电导致数据库报错,报错内容为“system01.dbf需要更多的恢复来保持一致性”。该Oracle数据库没有备份,仅有一些断断续续的归档日志。 Oracle数据库恢复流程: 1、检测数据库故障情况; 2、尝试挂起并修复数据库; 3、解析数据库文件; 4、导出并验证恢复的数据库文件。
|
7月前
|
缓存 关系型数据库 BI
使用MYSQL Report分析数据库性能(下)
使用MYSQL Report分析数据库性能
490 158
|
7月前
|
关系型数据库 MySQL 数据库
自建数据库如何迁移至RDS MySQL实例
数据库迁移是一项复杂且耗时的工程,需考虑数据安全、完整性及业务中断影响。使用阿里云数据传输服务DTS,可快速、平滑完成迁移任务,将应用停机时间降至分钟级。您还可通过全量备份自建数据库并恢复至RDS MySQL实例,实现间接迁移上云。
|
7月前
|
关系型数据库 MySQL 数据库
阿里云数据库RDS费用价格:MySQL、SQL Server、PostgreSQL和MariaDB引擎收费标准
阿里云RDS数据库支持MySQL、SQL Server、PostgreSQL、MariaDB,多种引擎优惠上线!MySQL倚天版88元/年,SQL Server 2核4G仅299元/年,PostgreSQL 227元/年起。高可用、可弹性伸缩,安全稳定。详情见官网活动页。
1225 152

推荐镜像

更多