在Java上备份mysql数据库

时间:2019-02-20 10:44:52

标签: java mysql wampserver

我尝试从Java应用程序(使用wamp服务器)备份mysql数据库,但是它不起作用,它始终显示消息“无法创建备份”。 这是我从此线程获取的代码: 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());
        }
    }

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

  1. 有关mysqldump命令的更多信息:https://stackoverflow.com/a/13484728/2987755
  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();