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成功");
    }

}

 

運行效果

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM