2013-01-24 183 views
0

我要採取數據庫的備份,但我不能恢復相同的備份文件。這是備份代碼。我想恢復數據庫

import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.util.zip.ZipEntry; 
import java.util.zip.ZipOutputStream; 

import javax.swing.JDialog; 
import javax.swing.JFileChooser; 

class Backupsql extends JDialog { 

    public boolean backupDB(String dbUser, String dbPass, String dbName) { 
     String sourcePath = null; 
     boolean result = false; 
     JFileChooser fc = new JFileChooser(); 
     int i = fc.showSaveDialog(Backupsql.this); 
     File file = fc.getSelectedFile(); 
     sourcePath = file.getPath(); 
     String filename = file.getName(); 
     sourcePath = sourcePath + ".sql"; 

     String executeCmd = 
      "C:\\Program Files\\MySQL\\MySQL Server 5.0\\bin\\mysqldump -u " 
      + dbUser + " -p" + dbPass + " " + dbName + " -r " + sourcePath; 

     Process runtimeProcess; 
     try { 
      runtimeProcess = Runtime.getRuntime().exec(executeCmd); 
      int processComplete = runtimeProcess.waitFor(); 
      if (processComplete == 0) { 
       System.out.println("Backup created successfully"); 
       compressFile(sourcePath); 
       result = true; 
      } else { 
       System.out.println("Could not create the backup"); 
      } 
     } catch (Exception e) { 
      // TODO: handle exception 
      System.out.println("error" + e); 
     } 
     return result; 
    } 

    public static void compressFile(String srcFile) { 
     byte[] buffer = new byte[1024]; 
     try { 
      String destPath = srcFile.replace(".sql", ".zip"); 
      FileOutputStream fos = new FileOutputStream(destPath); 
      ZipOutputStream zos = new ZipOutputStream(fos); 
      ZipEntry ze = new ZipEntry(srcFile); 
      zos.putNextEntry(ze); 
      FileInputStream in = new FileInputStream(srcFile); 

      int len; 
      while ((len = in.read(buffer)) > 0) { 
       zos.write(buffer, 0, len); 
      } 
      in.close(); 
      zos.closeEntry(); 
      zos.close(); 
      System.out.println("Done"); 
     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } 
    } 
} 

這是我使用的恢復命令。

String[] executeCmd = new String[]{ 
    "C:\\Program Files\\MySQL\\MySQL Server 5.5\\bin\\mysql.exe", "--user=" 
    + user, "--password=" + password, "-e", " source " + Unzippath}; 

我的代碼是否正確?我能得到一些建議嗎?

+2

你是什麼意思「不能」?你會得到什麼錯誤?您是否可以手動恢復備份(即不使用Java應用程序)? –

+0

是的,我能夠手動恢復備份 – VVV

+0

意味着我已經做了一個Java備份代碼以及Java恢復代碼,但代碼不工作的同一個文件。我無法通過Java恢復代碼恢復java備份文件 – VVV

回答

1

調查MySQL Backup/Restore。以下SQL可以簡單地使用JDBC執行,並且更一般。它還打算用於處理完整備份。

LOAD DATA INFILE '...'