JavaコードによるMysqlデータベースのバックアップとリカバリ

5265 ワード

本編はhttps://www.jianshu.com/p/92b019fc1effあ、私は自分で一部の修正をしました.以下はWindows環境下と書きますが、Linux環境下では違いも大きくなく、パスを変更すればいいです.
import java.io.*;
import java.net.URL;

public class DatabaseTool {

    public static void main(String[] args) {

        try {
            if (exportDatabase("127.0.0.1","3306","root","root",
                    "C:\\chengzheming\\backupDatabase","test-20190516.sql","test")
            ){
                System.out.println("       ");
            }else {
                System.out.println("       ");
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (importDatabase("127.0.0.1", "3306", "root", "root",
                "C:\\chengzheming\\backupDatabase", "test-20190516.sql", "test")) {
            System.out.println("       ");
        } else {
            System.out.println("       ");
        }
    }

    /**
     * Mysql     
     * @param hostIP      
     * @param hostPort   
     * @param userName    
     * @param password   
     * @param savePath     
     * @param fileName      
     * @param databaseName        
     * @return
     * @throws InterruptedException
     */
    public static boolean exportDatabase(String hostIP, String hostPort, String userName, String password, String savePath,
                                             String fileName, String databaseName) throws InterruptedException {
        //        
        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 {
            Runtime runtime = Runtime.getRuntime();

            //         ,                
            URL url = new URL("file:C:\\chengzheming\\develop software\\mysql-5.6.41-winx64\\bin");
            String path = url.getPath();

            //"mysqldump -h127.0.0.1 -uroot -P3306 -proot test"
            String cmd = "\\mysqldump -h" + hostIP + " -u" + userName + " -P" + hostPort + " -p" + password + " " + databaseName;

            cmd = path + cmd;
            Process process = runtime.exec(cmd);

            InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(), "utf8");
            bufferedReader = new BufferedReader(inputStreamReader);

            printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(savePath + fileName), "utf8"));
            String line;

            while ((line = bufferedReader.readLine()) != null) {
                printWriter.println(line);
            }
            printWriter.flush();
            if (process.waitFor() == 0) {
                return true;
            }

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

    /**
     *   Mysql   
     * @param hostIP      
     * @param hostPort   
     * @param userName    
     * @param password   
     * @param importFilePath        
     * @param sqlFileName        
     * @param databaseName         
     * @return
     * @throws InterruptedException
     */
    public static boolean importDatabase(String hostIP, String hostPort, String userName, String password, String importFilePath,
                                             String sqlFileName, String databaseName) {
        File imporFile = new File(importFilePath);
        if (!imporFile.exists()) {
            imporFile.mkdirs();
        }

        if (!importFilePath.endsWith(File.separator)) {
            importFilePath = importFilePath + File.separator;
        }

        //mysql -h127.0.0.1 -uroot -P3306 -p test

しかし、この方法には、ローカルC:\chengzheming\developソフトウェア\mysql-5.6.41-winx 64\binディレクトリがMySQLパスであるように、プログラムを導入するマシンがMySQLをインストールする欠陥があります.
手動バックアップリカバリデータベースも書き込み
データベースのバックアップ時にmysqlインストールディレクトリのbinディレクトリの下で以下のコマンドを実行するとmysqldump-h 127.0.0.1 -P3306 -uroot -proot test>C:\chengzheming\backupDatabase\test-20190516.sqlこの文の意味はバックアップアドレス127.0.0.1ポート3306ユーザーrootパスワードrootデータベースtestのデータをC:chengzhemingbackupDatabaseディレクトリの下でtest-20190516と名前を変更することです.sql
データベースを復元する際にディレクトリを規定する必要はなく、以下のコマンドを実行すればmysql-h 127.0.0.1-P 3306-uroot-proot testこの文の意味はC:/chengzheming/backupDatabasetest-20190516.sqlファイル内容はアドレス127.0.0.1ポート3306ユーザーrootパスワードrootのデータベースtestに復元される
注意-prootは警告を出す可能性があります.-pを書くだけで正常に動作します.
またmy.cnf(またはmy.ini)ファイル構成
[mysqldump]password=root
[mysql]password=root
警告を取り除くこともできます