Jun 16

使用java备份mysql数据库

admin , 16:19 , 数据库 » 数据库(MySql) , 评论(0) , 引用(0) , 阅读(2967) , Via 本站原创 | |
怎么手机十秒时时监控          拍拍购物综合频道 正品1折起 惊喜多多      拍拍女装特卖频道,汇集了最新的女装时尚新款 正品1折起,爱美的我还在等什么
     手机访问 就能天天 特价     电脑访问 爱淘宝go

基本原理:使用RunTime.exec执行mysql的备份命令“mysqldump”,再把执行结果记录到文件中,在执行下面方法前必须保证 mysqldump命令能用。代码如下:

package com.SpringMvcTest.util.dbAutoBackup;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class BackupMysqlDb {
 
 /**
  * www.itlife365.com
  * 完整备份MySQL的某个数据库
  * mysqldump –h hostname –u username –p password databasename > backupfile.sql
  * 例如:将192.168.102.2服务器上的book数据库备份到192.168.102.3
  * mysqldump -h 192.168.102.2 -u backup -p book >book.sql

  * @author happymen001
  * @version Jun 16, 2010  11:11:25 AM
  * @param hostName
  * @param dataBase
  * @param userName
  * @param passwd
  * @param outFilePath
  * @throws Exception
  * @return void
  */
 public static void backupMysqlDatabase(String hostName,String dataBase,String userName,
    String passwd,String outFilePath )throws Exception {
  //组装MySQL的备份命令
  StringBuilder sqlStr = new StringBuilder();
  sqlStr.append("mysqldump -u").append(userName)
    
     .append(" -p").append(passwd)
     .append(" ").append(dataBase);
  if(hostName != null && !hostName.equals("") ){
   sqlStr.append(" ")
         .append(" -h").append(hostName);
  }
  // --default-character-set=gb2312
  //调用系统cmd 命令执行备份命令
  Runtime rt = Runtime.getRuntime();
  Process process = rt.exec(sqlStr.toString());
  InputStream in = process.getInputStream();//控制台的输出信息作为输入流
  InputStreamReader isr = new InputStreamReader(in,"utf8");
  
  StringBuilder sb = new StringBuilder("");
  String inStr;
  //组合控制台输出信息字符串
  BufferedReader br = new BufferedReader(isr);
  while((inStr = br.readLine()) != null){
   sb.append(inStr)
    .append("\r\n");
  }
  
  //把备份数据写入到文件中
  FileOutputStream fout = new FileOutputStream (outFilePath);
  OutputStreamWriter writer = new OutputStreamWriter(fout,"utf8");
  writer.write(sb.toString());
  writer.flush();
  //写完文件,关闭相应的流
  in.close();
  isr.close();
  br.close();
  writer.close();
  fout.close();
 }
   
 /**
  * @author happymen001
  * @version Jun 15, 2010  11:26:46 PM
  * @param args
  * @return void
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  BackupMysqlDb  backupMysqlDb = new BackupMysqlDb ();
  String hostName = "127.0.0.1";
  String dataBase = "studentdb";//is
  String userName = "root";
  String passwd = "admin";
  String outFilePath = "D:\\backupmysql.sql";
  
  try {
   backupMysqlDb.backupMysqlDatabase(hostName,dataBase, userName, passwd, outFilePath);
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   System.out.println(" 备份MySQL失败");
  }
  System.out.println(" 备份MySQL 成功");
 }

}
 

参看:http://www.soluo.info/archives/61.html