2010-11-24 08:52:29  浏览:2552

java mysql 数据备份 还原

在ssh框架下,用hibernate的配置文件完成以下操作

首先,设置mysql的环境变量(在path中添加%MYSQL_HOME%in),重启电脑。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.struts2.ServletActionContext;
import org.hibernate.cfg.Configuration;
import org.hibernate.mapping.Table;

 

public class DataBaseUtil {
 private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
 private static Configuration configuration = new Configuration();
 private static String configFile = CONFIG_FILE_LOCATION;
 private static Properties properties = null;

 static {// 初始化hibernate配置文件
  try {
   configuration.configure(configFile);
   properties = configuration.getProperties();
  } catch (Exception e) {
   System.err.println("%%%% Error Creating configuration %%%%");
   e.printStackTrace();
  }
 }

 /**
  * getTableNameList方法概述:获取所有的表
  *
  * @return
  */
 public static List getTableNameList() {
  List tableNames = new ArrayList();
  for (Iterator iter = configuration.getTableMappings(); iter.hasNext();) {
   Table table = (Table) iter.next();
   String name = table.getName();
   if (!tableNames.contains(name)) {
    tableNames.add(name);
   }
  }
  return tableNames;
 }

 /**
  * backup方法概述:备份数据库
  *
  * @return
  */
 public static String backup(Map options,
   List tableNames) {
  Date date = new Date();
  SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
  String s = sdf.format(date);
  String fileName = ServletActionContext.getServletContext().getRealPath(
    "document")
    + "/" + s + ".sql";
  return backup(properties.getProperty("connection.username"), properties
    .getProperty("connection.password"), properties
    .getProperty("myeclipse.connection.profile"), fileName,
    tableNames);

 }

 /**
  * backup方法概述:备份数据库方法
  *
  * @param user
  *            数据库用户名
  * @param password
  *            数据库密码
  * @param database
  *            备份数据库名字
  * @param tables
  *            需要备份的表
  * @return
  */
 public static String backup(String userName, String password,
   String database, String fileName, List tables) {
  String outStr = null;
  try {
   Runtime rt = Runtime.getRuntime();
   String cmd = "mysqldump ";
   cmd += database;
   if (tables != null) {
    for (int i = 0; i < tables.size(); i++) {
     cmd += " " + tables.get(i);
    }
   }
   cmd += " -h192.168.1.200 -u" + userName + " -p" + password;
   // 调用 mysql 的 cmd:
   Process child = rt.exec(cmd);// 设置导出编码为utf8。这里必须是utf8

   // 把进程执行中的控制台输出信息写入.sql文件,即生成了备份文件。注:如果不对控制台信息进行读出,则会导致进程堵塞无法运行
   InputStream in = child.getInputStream();// 控制台的输出信息作为输入流

   InputStreamReader xx = new InputStreamReader(in, "utf8");// 设置输出流编码为utf8。这里必须是utf8,否则从流中读入的是乱码

   String inStr;
   StringBuffer sb = new StringBuffer("");

   // 组合控制台输出信息字符串
   BufferedReader br = new BufferedReader(xx);
   while ((inStr = br.readLine()) != null) {
    sb.append(inStr + " ");
   }
   outStr = sb.toString();
   FileOperationsUtil.saveSql(outStr);//写入到文件
   // 别忘记关闭输入输出流
   in.close();
   xx.close();
   br.close();
   // writer.close();
   // fout.close();
  } catch (Exception e) {
   System.out.println("/* 备份 " + database + " 数据库异常!" + e.getMessage()
     + " */");
  }
  return outStr;
 }

 /**
  * imports方法概述:还原数据库
  *
  * @param userName
  *            数据库登录名
  * @param password
  *            密码
  * @param database
  *            还原的数据库
  * @param filepath
  *            执行的sql文件(文件路径不能有空格)
  */
 public static boolean imports(String userName, String password,
   String database, String filepath) {
  boolean flag = false;
  // 新建数据库finacing
  String stmt1 = "mysqladmin -u " + userName + " -p" + password
    + " create " + database;
  // -p后面加的是你的密码
  String stmt2 = "mysql -u " + userName + " -p" + password + " "
    + database + " < " + filepath;
  String[] cmd = { "cmd", "/c", stmt2 };

  try {
   Runtime.getRuntime().exec(stmt1);
   Runtime.getRuntime().exec(cmd);
  } catch (IOException e) {
   e.printStackTrace();
  }
  return flag;
 }


 /**
  * restoreMysqlFromFile方法概述:还原数据库
  *
  * @param userName
  *            数据库用户名
  * @param password
  *            密码
  * @param database
  *            数据库名字
  * @param sql
  *            脚本
  * @return
  */

 public static boolean restoreMysqlFromFile(String userName,
   String password, String database, String sql) {
  boolean b = false;
  try {
   String stmt1 = "mysqladmin -u " + userName + " -p" + password
     + " create " + database;
   String stmt2 = "mysql -u " + userName + " -p" + password + " "
     + database;
   String[] cmd = { "cmd", "/c", stmt2 };
   Runtime.getRuntime().exec(stmt1);
   Runtime rt = Runtime.getRuntime();
   Process child = rt.exec(cmd);// 这里执行的是mysql命令,用户名,密码以及要恢复的数据库,命令执行完后会从我们上传的文件里面读取要执行的内容
   OutputStream out = child.getOutputStream();// 控制台的输入信息作为输出流
   OutputStreamWriter writer = new OutputStreamWriter(out, "utf8");
   writer.write(sql);
   // 注:这里如果用缓冲方式写入文件的话,会导致中文乱码,用flush()方法则可以避免
   writer.flush();
   // br.close();
   writer.close();
   out.close();
   // fis.close();
   b = true;
  } catch (Exception e) {
   e.printStackTrace();
  }
  return b;
 }

 /**
  * imports方法概述:还原数据
  *
  * @param filepath
  * @return
  */
 public static boolean imports(String Sql) {
  return restoreMysqlFromFile(properties
    .getProperty("connection.username"), properties
    .getProperty("connection.password"), properties
    .getProperty("myeclipse.connection.profile"), Sql);
 }
}

返回首页