efficacy
efficacy

Reputation: 70

Back up mysql database from java program

I'm trying to backup my database from a Java application. Currently, I'm using xampp as a localhost for database. I tried these codes in my program, but when I execute these codes my program goes on waiting state. When I execute the same code from command line it ask a password and after giving a password back up file backup.sql is created successfully. The code I'm using is:

String executeCmd = "C:\\xampp\\mysql\\bin\\mysqldump.exe -u root -p db1 -r D:/mine/backup.sql";

Java code:

    Process runtimeProcess;
    try {


        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();
    }

Upvotes: 2

Views: 1882

Answers (1)

Nishant
Nishant

Reputation: 55856

Try using the command with password in it, like

String executeCmd = "C:\\xampp\\mysql\\bin\\mysqldump.exe -u root -pYOUR_DB_PASSWORD db1 -r D:/mine/backup.sql";

Mind the NO SPACE between -p and the DATABASE PASSWORD.


Edit1: (from comment)

To resotre your database you need to execute

mysql -u root -pPASSWORD db1 < /full/qualified/path/to/backup.sql

Edit2: (improvements)

You may also want to try some of the cool options like

mysqldump --user MYSQL_USER --password=MYSQL_PASSWORD --add-locks --flush-privileges \
--add-drop-table --complete-insert --extended-insert --single-transaction \
--database DB_TO_BACKUP > FILENAME_FOR_SQL_STATEMENTS

Refer here.

Upvotes: 2

Related Questions