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,如需转载请自行联系原作者


相关文章
|
13天前
|
DataWorks Oracle 关系型数据库
DataWorks操作报错合集之尝试从Oracle数据库同步数据到TDSQL的PG版本,并遇到了与RAW字段相关的语法错误,该怎么处理
DataWorks是阿里云提供的一站式大数据开发与治理平台,支持数据集成、数据开发、数据服务、数据质量管理、数据安全管理等全流程数据处理。在使用DataWorks过程中,可能会遇到各种操作报错。以下是一些常见的报错情况及其可能的原因和解决方法。
30 0
|
3天前
|
Oracle Java 关系型数据库
【服务器】python通过JDBC连接到位于Linux远程服务器上的Oracle数据库
【服务器】python通过JDBC连接到位于Linux远程服务器上的Oracle数据库
14 6
|
3天前
|
SQL Oracle 关系型数据库
零基础入门 Oracle数据库:轻松上手
零基础入门 Oracle数据库:轻松上手
6 0
|
3天前
|
Oracle 关系型数据库 Java
java操作多数据源将oracle数据同步达梦数据库
java操作多数据源将oracle数据同步达梦数据库
|
4天前
|
SQL Java 数据库连接
JDBC Java标准库提供的一些api(类+方法) 统一各种数据库提供的api
JDBC Java标准库提供的一些api(类+方法) 统一各种数据库提供的api
9 0
|
4天前
|
存储 Oracle 关系型数据库
oracle 数据库 迁移 mysql数据库
将 Oracle 数据库迁移到 MySQL 是一项复杂的任务,因为这两种数据库管理系统具有不同的架构、语法和功能。
15 0
|
13天前
|
存储 大数据 测试技术
矢量数据库的性能测试与评估方法
【4月更文挑战第30天】本文探讨了矢量数据库的性能测试与评估方法,强调其在大数据和AI时代的重要性。文中介绍了负载测试、压力测试、容量测试、功能测试和稳定性测试五大评估方法,以及实施步骤,包括确定测试目标、设计用例、准备环境、执行测试和分析结果。这些方法有助于确保数据库的稳定性和高效性,推动技术发展。
|
13天前
|
关系型数据库 MySQL PHP
【PHP 开发专栏】PHP 连接 MySQL 数据库的方法
【4月更文挑战第30天】本文介绍了 PHP 连接 MySQL 的两种主要方法:mysqli 和 PDO 扩展,包括连接、查询和处理结果的基本步骤。还讨论了连接参数设置、常见问题及解决方法,如连接失败、权限和字符集问题。此外,提到了高级技巧如使用连接池和缓存连接信息以优化性能。最后,通过实际案例分析了在用户登录系统和数据管理中的应用。
|
13天前
|
SQL 关系型数据库 MySQL
利用 SQL 注入识别数据库方法总结
利用 SQL 注入识别数据库方法总结
|
14天前
|
API 数据库 Python
Python web框架fastapi数据库操作ORM(二)增删改查逻辑实现方法
Python web框架fastapi数据库操作ORM(二)增删改查逻辑实现方法