how to backup and restore mysql database using java

喜你入骨 提交于 2019-12-04 15:44:57

I don't think you are using the mysqldump command quite right. Shouldnt you use < or > characters to denote the backup/restore? This is discussed at length here. Something like this to backup:

String command = "mysqldump --host=" + dataBase.getHost() + " --user=" + dataBase.getUserName() + " --password=" + dataBase.getPassword() + " "
            + dataBase.getDatabaseName() + " > " + dataBase.getBackupPath() + "/ofm_mnu_backup_" + bkDate + ".sql";

and to restore:

String command = "mysqldump --host=" + dataBase.getHost() + " --user=" + dataBase.getUserName() + " --password=" + dataBase.getPassword() + " "
            + dataBase.getDatabaseName() + " < " + dataBase.getBackupPath() + "/ofm_mnu_backup_" + bkDate + ".sql";
Ballans

I would like to thank you guys for the support on how to restore mysql database with java code. Since none of the codes worked for me, but it gave me a clue to teak it to work.

Below is my final working code.

String[] executeCmd = new String[]{"C:\\xampp\\mysql\\bin\\mysql.exe",mydb, "--user=" + dbUserName, "--password=" + dbPassword, "-e", " source " + source};

Maybe its because of output stream assigned to the terminal... Is it an option to run your mysqldump command inside the cmd? for example

String command = "cmd /K mysqldump..."

you might be also interested to read this article:

Hope, this helps

this really work for restore

 String comando = "C:\\MySQL\\bin\\mysql.exe  --host=localhost --port=3306 --user=root --password=123 < D:\\back.sql";
File f = new File("restore.bat");
FileOutputStream fos = new FileOutputStream(f);
fos.write(comando.getBytes());
fos.close();
Process run = Runtime.getRuntime().exec("cmd /C start restore.bat ");  

and for backup

  DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.forLanguageTag("ru"));
    java.util.Date currentDate = new java.util.Date();
    Process p = null;
    try {
        Runtime runtime = Runtime.getRuntime();
        p = runtime.exec("C:\\MySQL\\bin\\mysqldump.exe  --default-character-set=utf8 -uroot -p123 -c  -B shch2 -r " + "D:/" + dateFormat.format(currentDate) + "_backup" + ".sql");

//change the dbpass and dbname with your dbpass and dbname int processComplete = p.waitFor();

        if (processComplete == 0) {

            System.out.println("Backup created successfully!");

        } else {
            System.out.println("Could not create the backup");
        }


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

but you need to convey the exact path to mysql.exe and mysqldump.exe

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!