使用java备份mysql数据库

基本原理:使用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

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

«    2025年1月    »
12345
6789101112
13141516171819
20212223242526
2728293031
搜索
标签列表
网站分类
最新留言
    文章归档
    友情链接

    Powered By Z-BlogPHP 1.7.3

    Copyright Your WebSite.Some Rights Reserved.闽ICP备11018667号-2