Gapchoos
Gapchoos

Reputation: 1422

MySql backup is not working

String[] executeCmd = new String[] { "mysql", "-u",DB_USER,"-p"+DB_PASSWORD,DB_NAME, " < ", "\""+FileName+"\"" };

Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
System.out.println("processComplete: " + processComplete);

This is the code I have worked with. The program hangs when the "waitFor()" method is called.

How to solve this?

Upvotes: 1

Views: 369

Answers (3)

msl
msl

Reputation: 107

In case you don't set a password for XAMPP, don't use -p

public class Testbackupmysql {
public boolean tbBackup(String dbName,String dbUserName, String path) {

    String executeCmd = "C:\\xampp\\mysql\\bin\\mysqldump -u " + dbUserName + " --add-drop-database -B " + dbName + " -r " + path;
    Process runtimeProcess;
        try
        {
            System.out.println(executeCmd);//this out put works in mysql shell
            runtimeProcess = Runtime.getRuntime().exec(executeCmd);
            int processComplete = runtimeProcess.waitFor();

                if (processComplete == 0)
                {
                    System.out.println("Backup created successfully");
                    return true;
                }
                else
                {
                    System.out.println("Could not create the backup");
                }
        } catch (Exception ex)
        {
            ex.printStackTrace();
        }
return false;
}

public static void main(String[] args){

    Testbackupmysql bb = new Testbackupmysql();
        bb.tbBackup("your_database_name","your_db_username","D:\\123.sql");

}

}

Upvotes: 0

Gapchoos
Gapchoos

Reputation: 1422

    String[] command = new String[]{"mysql", Constants.DB_NAME, "-u" + Constants.DB_USER, "-p" + Constants.DB_PASSWORD, "-e", " source "+FileName };

    try {
            Process runtimeProcess = Runtime.getRuntime().exec(command);
            int processComplete = runtimeProcess.waitFor();
            if (processComplete == 0)
            {
                System.out.println("DatabaseManager.restore: Restore Successfull");

            }
            else 
            {
                System.out.println("DatabaseManager.restore: Restore Failure!");
            }

        return true;

    }

    catch (final Exception ex) 
    {
        Application.showErrorInConsole(ex);
        NmsLogger.writeErrorLog("Database Restore failed ", ex.toString());
        NmsLogger.writeDebugLog(ex);
        return false;

    }

The above code worked fine for me :)

Upvotes: 0

John Woo
John Woo

Reputation: 263723

you need to add spaces after the parameters, don't use array

String executeCmd = "mysqldump ", " -u ",DB_USER," -p " + DB_PASSWORD, + " " + DB_NAME, " < ", "\""+FileName+"\"" ;

and the cleaner way is to use String.Format()

String executeCmd = String.Format("mysqldump -u %s -p %s %s < \"%s\"", DB_USER, DB_PASSWORD, DB_NAME, FileName)

Upvotes: 5

Related Questions