在 java 上备份 mysql 数据库

back-up mysql database on java

我已经尝试从我的 java 应用程序(使用 wamp 服务器)备份 mysql 数据库,但它不起作用,它总是显示消息 "can't create backup"。 这是我从这个线程中获取的代码: Backup a mysql [xampp] database in java

    public static void saveBdd(){
         String path = null;
         String user = "root";
         Process p = null;


         JFileChooser fc = new JFileChooser();
         fc.setDialogTitle("Choisir l'emplacement de la sauvegarde");
         fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
         fc.setAcceptAllFileFilterUsed(false);
         fc.showOpenDialog(startPage);
         String date = new SimpleDateFormat("dd-MM-yyyy").format(new Date());

        try {
            File f = fc.getSelectedFile();
            path = f.getAbsolutePath();
            path = path.replace('\', '/');
            path = path+"/bcpbdd_"+date+".sql";


        } catch (Exception e) {
            e.printStackTrace();
        }
        try{
            Runtime runtime = Runtime.getRuntime();

            p=runtime.exec("C:/wamp64/bin/mysql/mysql5.7.23/bin/mysqldump -u " + user + " --add-drop-database -B bcpbdd -r "+path);

            int processComplete = p.waitFor();
            if (processComplete==0) {
                StartPage.afficheMessage("Backup Created Success!");
            } else {
                 StartPage.afficheMessage("Can't create backup.");
            }
        } catch (Exception e) {
            StartPage.afficheMessage(e.getMessage());
        }
    }

您可以使用 p.getErrorStream()p.getInputStream() 读取过程的输出 这应该在一个新线程中完成,然后您可以将输出写入日志文件或控制台。

这是我尝试过的并且工作正常,

  1. 有关 mysqldump 命令的更多信息:
  2. 您可以提供要创建备份文件的任何路径db_backup.sql

    Process rt = Runtime.getRuntime().exec("mysqldump -P 3306 -h 127.0.0.1 -u root test");
    int exitCode = rt.waitFor();
    System.out.println("Process exited with : " + exitCode);
    BufferedReader in = new BufferedReader(new InputStreamReader(rt.getInputStream()));
    BufferedReader err = new BufferedReader(new InputStreamReader(rt.getErrorStream()));
    
    System.out.println("Backup file output:");
    String line;
    BufferedReader reader;
    if (exitCode != 0) {
        reader = err;
    } else {
        reader = in;
    }
    File file = new File("db_backup.sql");
    
    BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
        bufferedWriter.write(line);
        bufferedWriter.newLine();
    }
    bufferedWriter.flush();
    bufferedWriter.close();