mysql 完全备份

//mysql 完全备份实现类

package com.sky.mysql;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Properties;
public class MySqlBackup {

 public void backup() throws IOException {

  Properties pros = new BackupUtil().getPprVue("pro.properties");// 读取db文件
  String username = pros.getProperty("username");//用户名
  String password = pros.getProperty("password");//密码 
  String dataName=pros.getProperty("dataName");//数据库
  String address = pros.getProperty("address");//ip地址
  //C:\Program Files\MySQL\MySQL Server 5.0\bin
  String mysqldump="C:\\Program Files\\MySQL\\MySQL Server 5.0\\bin\\mysqldump";//mysql安装目录
  String savePath = pros.getProperty("savePath");//保存的路径
  StringBuffer sb = new StringBuffer();
  
  sb.append(mysqldump);
  sb.append(" -u ");
  sb.append(username);
  sb.append(" ");
  sb.append("-p");
  sb.append(password+" ");
  sb.append(dataName);
  sb.append(" ");
  sb.append("-h ");
  sb.append(address);
  System.out.println("\n\t<-------------数据库备份开始------------->");
  try {
   Runtime rt = Runtime.getRuntime();
   Process process = rt.exec(sb.toString());// 执行命令
   InputStream in = process.getInputStream();// 控制台的输出信息作为输入流
   InputStreamReader inputRead = new InputStreamReader(in, "utf8");// 设置输出流编码为utf8   
   File backupath = new File(savePath);
   if (!backupath.exists()) {
    backupath.mkdir();
   }   
   String sqlname=new BackupUtil().getTime();//文件名
   String filePath = savePath+File.separator + sqlname;//文件路径
   OutputStream outputStream = new FileOutputStream(filePath);   
   byte[] buff = new byte[512];
   int len;
   while ((len = in.read(buff)) != -1) {
    outputStream.write(buff, 0, len);
   }
   in.close();
   inputRead.close();   
   outputStream.close();
  } catch (Exception e) {
   e.printStackTrace();
  }  
  System.out.println("\n\t<-------------数据库备份结束-------------->");
 }

 public static void main(String[] args) throws IOException {
   new MySqlBackup().backup();//数据库备份
 }
}

 

 

 

//mysql 完全备份工具类

package com.sky.mysql;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

public class BackupUtil {

 public Properties getPprVue(String string) {
//  BackmysqlUtil.class.getClassLoader().getResourceAsStream(string);
  InputStream input=BackupUtil.class.getClassLoader().getResourceAsStream(string);
  Properties pro=new Properties();
  try {
   pro.load(input);
  } catch (IOException e) {
   e.printStackTrace();
  }
  return pro;
 }
 
 public String getTime(){
  Date d = new Date();
  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hhmmss");
  String s =sdf.format(d);
  return s;
 }
}

 

 

 

//mysql 完全备份properties文件

 

username=root
password=1
address=127.0.0.1
savePath=e:\\backup
dataName=pkb

你可能感兴趣的:(mysql 完全备份)