Search code examples
javamysqlwampserver

back-up mysql database on java


I've tried to back-up mysql database from my java app (using wamp server) but it doesn't work, it always display the message "can't create backup". here's my code which I took from this thread : 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());
        }
    }

Solution

  • You can read the output of the process using p.getErrorStream() and p.getInputStream() This should be done in a new Thread and then you can write the output into a log file or into the console.