0

0

Java备份还原Mysql数据库

大家讲道理

大家讲道理

发布时间:2016-11-10 10:55:42

|

1311人浏览过

|

来源于php中文网

原创

///实体类
package com.ews.util;
/**
 * 系统备份展示对象
 * 
 * */
public class DataFile {
 private String fileName;//备份文件的名称
 private String fileDate;//备份文件的日期
 private String filePath;//备份文件的地址
 private String fileSize;//备份文件的大小
 public String getFileSize() {
  return fileSize;
 }
 public void setFileSize(String fileSize) {
  this.fileSize = fileSize;
 }
 public String getFileName() {
  return fileName;
 }
 public void setFileName(String fileName) {
  this.fileName = fileName;
 }
 public String getFileDate() {
  return fileDate;
 }
 public void setFileDate(String fileDate) {
  this.fileDate = fileDate;
 }
 public String getFilePath() {
  return filePath;
 }
 public void setFilePath(String filePath) {
  this.filePath = filePath;
 }
}
  
///实现备份代码
package com.ews.action;
  
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.sql.Date;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
  
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.fileupload.FileItem;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
  
import com.ews.util.DataFile;
  
public class DataAction extends EwsAction{
 private String username;
 private String password;
 private String host;
 private String PORT;
 private String dbname;
 private List dataFiles = new ArrayList();
 private File reductionFile;
 public File getReductionFile() {
  return reductionFile;
 }
 public void setReductionFile(File reductionFile) {
  this.reductionFile = reductionFile;
 }
 public List getDataFiles() {
  return dataFiles;
 }
 public void setDataFiles(List dataFiles) {
  this.dataFiles = dataFiles;
 }
 public String getHost() {
  return host;
 }
 public void setHost(String host) {
  this.host = host;
 }
 public String getPORT() {
  return PORT;
 }
 public void setPORT(String pORT) {
  PORT = pORT;
 }
 public String getUsername() {
  return username;
 }
 public void setUsername(String username) {
  this.username = username;
 }
 public String getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }
 public String getDbname() {
  return dbname;
 }
 public void setDbname(String dbname) {
  this.dbname = dbname;
 }
 /**
  * 删除
  * */
 public String delete(){
  String fileName = request.getParameter("fileName");
  System.out.println(fileName);
  String backPath = ServletActionContext.getServletContext().getRealPath("/")+"ewssite/back/"+fileName;
  File file = new File(backPath);
  file.delete();
  return "delete";
 }
 /**
  * 得到备份文件的List集合
  * 
  * */
 public String findList(){
  String backPath = ServletActionContext.getServletContext().getRealPath("/")+"ewssite/back/";
  File file = new File(backPath);
  if (!file.exists())
   return "findListData";
  File[] file1 = file.listFiles();
  for (int i = 0; i < file1.length; i++) {
   if(file1[i].getName().equals("ramdit.txt")) continue;
   SimpleDateFormat sdf= new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
   //前面的lSysTime是秒数,先乘1000得到毫秒数,再转为java.util.Date类型
   java.util.Date dt = new Date(file1[i].lastModified());  
   String sDateTime = sdf.format(dt);  //得到精确到秒的表示:08/31/2006 21:08:00
   DataFile dataFile = new DataFile();
   dataFile.setFileName(file1[i].getName());
   dataFile.setFileDate(sDateTime);
   String path = request.getContextPath();
   String filePath = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()+ path + "/ewssite/back/"+file1[i].getName();
   dataFile.setFilePath(filePath);
   DecimalFormat   df   =   new   DecimalFormat( ".## "); 
   dataFile.setFileSize(df.format(file1[i].length()/1024000f));
   dataFiles.add(dataFile);
  }
  return "findListData";
 }
 /**
  * 配置  Mysql bin目录
  * */
 public void getConfig(){
  ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
  BasicDataSource ba = (BasicDataSource)context.getBean("dataSource");
  setUsername(ba.getUsername());
  setPassword(ba.getPassword());
  String url = ba.getUrl();
  url = url.substring(13, url.length());
  String[] temp = url.split("/");
  String[] temp1 = temp[0].split(":");
  setHost(temp1[0]);
  setPORT(temp1[1]);
  for (int i = 0; i < temp[1].length(); i++) {
   String temp2 = temp[1].charAt(i)+"";
   if(temp2.equals("?")){
    setDbname(temp[1].substring(0,5));
   }
  }
 }
 /**
  * 备份
  * */
 public String backup(){
  getConfig();
  //得到配置文件
  try {
   Runtime rt = Runtime.getRuntime();
   String backPath = ServletActionContext.getServletContext().getRealPath("/")+"ewssite/back/"+System.currentTimeMillis()+".sql";   
   String mysql = "mysqldump -u" + getUsername()+ " -p" + getPassword() + " --default-character-set=utf8 -h"+getHost()+" -P"+getPORT()+" " + getDbname() +" >"+"\""+backPath+"\"";   
   Process proc = rt.exec("cmd.exe /c "+mysql);// 设置导出编码为utf8。这里必须是utf8
   //String backExe = ServletActionContext.getServletContext().getRealPath("/")+"bin/mysqldump.exe"; 
   //String mysql = getDbname()+ " -u" + getUsername()+ " -p" + getPassword() + " --default-character-set=utf8 -h"+getHost()+" -P"+getPORT()+" >"+"\""+backPath+"\""; 
   int tag = proc.waitFor();// 等待进程终止  
  } catch (Exception e) {
   e.printStackTrace();
  }
  return "backup";
 }
 /**
  * 还原
  * */
 public String load(){
  String sqlPath="";
  if(request.getParameter("selectName")!=null)
   sqlPath = request.getParameter("selectName");
  if(reductionFile!=null){
   String name = upload(reductionFile);
   sqlPath = ServletActionContext.getServletContext().getRealPath("/")+"ewssite/back/" + name;
  }
//  System.out.println(sqlPath);
  if(sqlPath.substring(sqlPath.lastIndexOf(".")+1).equals("sql")){
   getConfig();
   setHost("127.0.0.1");
   setUsername("root");
   setPassword("root");
   setDbname("test");
   //得到配置文件
   try {
    Runtime rt = Runtime.getRuntime();
    String createDb = "mysqladmin -u" + getUsername()+ " -p" + getPassword() + " create "+getDbname();
    String mysql = "mysql -u" + getUsername()+ " -p" + getPassword() + " "+getDbname()+" <"+"\""+ sqlPath+"\"";//+"\""+backPath+"\""
    rt.exec("cmd.exe /c "+createDb);
    Process proc  = rt.exec("cmd.exe /c "+mysql);
    int tag = proc.waitFor();// 等待进程终止
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
  return "load";
 }
 /**
  * 把本地的数据库备份文件上传到服务器上
  * file:从前台获取的file
  * */
 public String upload(File file ){
  String name = "";
  try {
   DataInputStream in = new DataInputStream(new FileInputStream(file));
//   FileInputStream in = new FileInputStream(file);
     
   String backPath = ServletActionContext.getServletContext().getRealPath("/")+"ewssite/back/";
   name = System.currentTimeMillis()+".sql";
   backPath = backPath + name;
//   FileOutputStream out = new FileOutputStream(new File(backPath));
   DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(backPath)));
   int b = -1;
   while ((b = in.read()) != -1) {
    out.write(b);
   }
   out.close();
   in.close();
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return name;
 }
}

相关文章

java速学教程(入门到精通)
java速学教程(入门到精通)

java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
PHP 表单处理与文件上传安全实战
PHP 表单处理与文件上传安全实战

本专题聚焦 PHP 在表单处理与文件上传场景中的实战与安全问题,系统讲解表单数据获取与校验、XSS 与 CSRF 防护、文件类型与大小限制、上传目录安全配置、恶意文件识别以及常见安全漏洞的防范策略。通过贴近真实业务的案例,帮助学习者掌握 安全、规范地处理用户输入与文件上传的完整开发流程。

1

2026.01.13

PPT交互图表教程大全
PPT交互图表教程大全

本专题整合了PPT交互图表相关教程汇总,阅读专题下面的文章了解更多详细内容。

41

2026.01.12

Java 项目构建与依赖管理(Maven / Gradle)
Java 项目构建与依赖管理(Maven / Gradle)

本专题系统讲解 Java 项目构建与依赖管理的完整体系,重点覆盖 Maven 与 Gradle 的核心概念、项目生命周期、依赖冲突解决、多模块项目管理、构建加速与版本发布规范。通过真实项目结构示例,帮助学习者掌握 从零搭建、维护到发布 Java 工程的标准化流程,提升在实际团队开发中的工程能力与协作效率。

19

2026.01.12

c++主流开发框架汇总
c++主流开发框架汇总

本专题整合了c++开发框架推荐,阅读专题下面的文章了解更多详细内容。

134

2026.01.09

c++框架学习教程汇总
c++框架学习教程汇总

本专题整合了c++框架学习教程汇总,阅读专题下面的文章了解更多详细内容。

66

2026.01.09

学python好用的网站推荐
学python好用的网站推荐

本专题整合了python学习教程汇总,阅读专题下面的文章了解更多详细内容。

139

2026.01.09

学python网站汇总
学python网站汇总

本专题整合了学python网站汇总,阅读专题下面的文章了解更多详细内容。

13

2026.01.09

python学习网站
python学习网站

本专题整合了python学习相关推荐汇总,阅读专题下面的文章了解更多详细内容。

19

2026.01.09

俄罗斯手机浏览器地址汇总
俄罗斯手机浏览器地址汇总

汇总俄罗斯Yandex手机浏览器官方网址入口,涵盖国际版与俄语版,适配移动端访问,一键直达搜索、地图、新闻等核心服务。

105

2026.01.09

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Git 教程
Git 教程

共21课时 | 2.6万人学习

Kotlin 教程
Kotlin 教程

共23课时 | 2.5万人学习

PHP新手语法线上课程教学
PHP新手语法线上课程教学

共13课时 | 0.8万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号