1. 程式人生 > 實用技巧 >Java中使用mysqldump實現mysql資料庫備份並將sql檔案打成zip壓縮包

Java中使用mysqldump實現mysql資料庫備份並將sql檔案打成zip壓縮包

場景

在Java程式碼中呼叫mysqldump命令實現對指定的mysql資料庫和指定的表匯出為sql檔案。

並將sql檔案進行壓縮成zip儲存備份。

mysqldump 簡介

mysqldump 是 MySQL 自帶的邏輯備份工具。

它的備份原理是通過協議連線到 MySQL 資料庫,將需要備份的資料查詢出來,將查詢出的資料轉換成對應的insert 語句,當我們需要還原這些資料時,只要執行這些 insert 語句,即可將對應的資料還原。

要想使用我們需要找到mysql安裝目錄下的bin下的mysqldump.exe

因為沒有將其新增到環境變數中,所以需要找到其所在的全路徑。

注:

部落格:

https://blog.csdn.net/badao_liumang_qizhi
關注公眾號
霸道的程式猿
獲取程式設計相關電子書、教程推送與免費下載。

實現

首先需要宣告一些執行mysqldump的變數

    private static String hostIP = "127.0.0.1";
    private static String userName = "root";
    private static String password = "123456";
    //sql檔案儲存的路徑
    private static String savePath = "D:/bak
"; //sql檔案儲存名 private static String fileName = "badaoBak"+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+".sql"; //資料庫名 private static String databaseName = "test"; private static final int BUFFER = 8192; //zip壓縮包儲存路徑 private static String zipPath = "D:/bak/badao.zip";

然後新建方法用語執行sql的匯出

    /**
     * 執行資料備份
     * @return
     */
    public static String dataBakExec()
    {
        String sqlFilePath = "";
        File saveFile = new File(savePath);
        // 如果目錄不存在
        if (!saveFile.exists()) {
            // 建立資料夾
            saveFile.mkdirs();
        }
        if(!savePath.endsWith(File.separator)){
            savePath = savePath + File.separator;
        }

        PrintWriter printWriter = null;
        BufferedReader bufferedReader = null;
        try {
            printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(savePath + fileName), "utf8"));
            sqlFilePath= savePath + fileName;
            //匯出指定資料庫指定表的結構和資料
            Process process = Runtime.getRuntime().exec("C:/Program Files/MySQL/MySQL Server 5.6/bin/mysqldump -h" + hostIP + " -u" + userName + " -p" + password + " --set-charset=UTF8 " + databaseName +" book ");
            //匯出指定資料庫指定表的結構
            //Process process = Runtime.getRuntime().exec("C:/Program Files/MySQL/MySQL Server 5.6/bin/mysqldump -h" + hostIP + " -u" + userName + " -p" + password + " --set-charset=UTF8 " + databaseName + " book -d");
            //匯出指定資料庫指定表符合條件的結構和資料
            //Process process = Runtime.getRuntime().exec("C:/Program Files/MySQL/MySQL Server 5.6/bin/mysqldump -h" + hostIP + " -u" + userName + " -p" + password + " --set-charset=UTF8 " + databaseName +" book "+" --where=\" price> 100" + "\" ");
            InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(), "utf8");
            bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            while((line = bufferedReader.readLine())!= null){
                printWriter.println(line);
            }
            printWriter.flush();
            //0 表示執行緒正常終止。
            if(process.waitFor() == 0){
                System.out.println("備份資料成功");

            }
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (printWriter != null) {
                    printWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return  sqlFilePath;
    }

注意把這裡的mysqldump的路徑改為自己的路徑。

執行的命令如果不加具體的資料庫則匯出所有的表,資料庫後面加表明則是匯出具體的表。

並且還可以選擇匯出表的結構和資料以及符合要求的表資料。

具體自行搜尋musqldump命令。

備份sql效果

sql備份成功後將其路徑返回,然後再新建一個生成zip壓縮包的方法

  /**
     * 壓縮sql檔案為zip
     * @param filePath sql檔案路徑
     * @param zipPath  要生成的zip壓縮包路徑
     */
    public static void zipFile(String filePath,String zipPath) {
        ZipOutputStream out = null;
        try {
            out = new ZipOutputStream(new FileOutputStream(zipPath));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //得到檔案列表資訊
        File file = new File(filePath);
        // 壓縮zip包
        try {
            if (!file.exists()) {
                return;
            }
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            try {

                ZipEntry entry = new ZipEntry(file.getName());
                out.putNextEntry(entry);
                int count;
                byte data[] = new byte[BUFFER];
                while ((count = bis.read(data, 0, BUFFER)) != -1) {
                    out.write(data, 0, count);
                }

            } catch (Exception e) {
                throw new RuntimeException(e);
            }finally {
                out.closeEntry();
                bis.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("生成zip成功");
    }

然後完整的main方法示例程式碼

package com.badao.mysqlbak;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class MysqlBakMain {

    private static String hostIP = "127.0.0.1";
    private static String userName = "root";
    private static String password = "123456";
    //sql檔案儲存的路徑
    private static String savePath = "D:/bak";
    //sql檔案儲存名
    private static String fileName = "badaoBak"+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+".sql";
    //資料庫名
    private static String databaseName = "test";
    private static final int BUFFER = 8192;
    //zip壓縮包儲存路徑
    private static String zipPath = "D:/bak/badao.zip";


    public static void main(String[] args) {
        String sqlFilePath = dataBakExec();
        System.out.println("備份的sql檔案儲存路徑為:"+sqlFilePath);
        zipFile(sqlFilePath,zipPath);
    }

    /**
     * 執行資料備份
     * @return
     */
    public static String dataBakExec()
    {
        String sqlFilePath = "";
        File saveFile = new File(savePath);
        // 如果目錄不存在
        if (!saveFile.exists()) {
            // 建立資料夾
            saveFile.mkdirs();
        }
        if(!savePath.endsWith(File.separator)){
            savePath = savePath + File.separator;
        }

        PrintWriter printWriter = null;
        BufferedReader bufferedReader = null;
        try {
            printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(savePath + fileName), "utf8"));
            sqlFilePath= savePath + fileName;
            //匯出指定資料庫指定表的結構和資料
            Process process = Runtime.getRuntime().exec("C:/Program Files/MySQL/MySQL Server 5.6/bin/mysqldump -h" + hostIP + " -u" + userName + " -p" + password + " --set-charset=UTF8 " + databaseName +" book ");
            //匯出指定資料庫指定表的結構
            //Process process = Runtime.getRuntime().exec("C:/Program Files/MySQL/MySQL Server 5.6/bin/mysqldump -h" + hostIP + " -u" + userName + " -p" + password + " --set-charset=UTF8 " + databaseName + " book -d");
            //匯出指定資料庫指定表符合條件的結構和資料
            //Process process = Runtime.getRuntime().exec("C:/Program Files/MySQL/MySQL Server 5.6/bin/mysqldump -h" + hostIP + " -u" + userName + " -p" + password + " --set-charset=UTF8 " + databaseName +" book "+" --where=\" price> 100" + "\" ");
            InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(), "utf8");
            bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            while((line = bufferedReader.readLine())!= null){
                printWriter.println(line);
            }
            printWriter.flush();
            //0 表示執行緒正常終止。
            if(process.waitFor() == 0){
                System.out.println("備份資料成功");

            }
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (printWriter != null) {
                    printWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return  sqlFilePath;
    }

    /**
     * 壓縮sql檔案為zip
     * @param filePath sql檔案路徑
     * @param zipPath  要生成的zip壓縮包路徑
     */
    public static void zipFile(String filePath,String zipPath) {
        ZipOutputStream out = null;
        try {
            out = new ZipOutputStream(new FileOutputStream(zipPath));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //得到檔案列表資訊
        File file = new File(filePath);
        // 壓縮zip包
        try {
            if (!file.exists()) {
                return;
            }
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            try {

                ZipEntry entry = new ZipEntry(file.getName());
                out.putNextEntry(entry);
                int count;
                byte data[] = new byte[BUFFER];
                while ((count = bis.read(data, 0, BUFFER)) != -1) {
                    out.write(data, 0, count);
                }

            } catch (Exception e) {
                throw new RuntimeException(e);
            }finally {
                out.closeEntry();
                bis.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("生成zip成功");
    }

}

執行效果