Mysql數據庫備份與還原

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

public class BackupMysql {
 /** 訪問MySQL數據庫服務器所在的url */
 private String serverUrl;
 /** 訪問MySQL數據庫的用戶名 */
 private String username;
 /** 訪問MySQL數據庫的密碼 */
 private String password;

 
 public String getServerUrl() {
  return serverUrl;
 }

 public void setServerUrl(String serverUrl) {
  this.serverUrl = serverUrl;
 }

 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 BackupMysql(String serverUrl,String username, String password) {
  super();
  this.serverUrl=serverUrl;
  this.username = username;
  this.password = password;
 }

 public String backup(String backupPath, String dbName) throws IOException {

  String backupFile = backupPath+ dbName+ new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date()) + ".sql";

  String mysql = "mysqldump "+"–host="+serverUrl+" –user=" + username + " –password="+ password + " –opt " + dbName + "> " + backupFile;

  java.lang.Runtime.getRuntime().exec("cmd /c " + mysql);
  
  System.out.println("備份成功!");
 
  return backupFile;

 }

 public void restore(String restoreFile, String dbName) throws Exception {
 
  String mysql = "mysql "+"-h"+serverUrl+" -u" + username + " -p"+ password + " " + dbName + " < " + restoreFile;
 
        System.out.println(mysql);
       
  java.lang.Runtime.getRuntime().exec("cmd /c " + mysql);
 
  System.out.println("還原成功!");
 }

 /**
  * @param args
  */
 public static void main(String[] args) {

  String serverUrl="127.0.0.1";
 
  String userName = "root";

  String pwd = "root";

  BackupMysql backup = new BackupMysql(serverUrl,userName, pwd);

  try {
   backup.restore("d:/nationz2010-12-20-14-16-47.sql", "nationz");
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}

 
摘自 gdn_wolf的專欄

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。