简体   繁体   中英

Automatic backup of MySql DB daily based on scheduled time through Java

I am trying to backup mysql DB from Java application (IDE Eclipse) based on schedule time(daily) but can't seem to find the file in the specified path. printing else part in the console, not getting where I am going wrong.. Please anybody help me out to resolve this.. Thanks in advance..

package com.cerner.automation.eboard.service;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
public class UtilityService {

// Destination to create dump-date.sql file on daily basis
private static final String repo = "\"C:/DB_backup/dump-date.sql\""; //$NON-NLS-1$

/*
 * sec min hour(24) * & ? this is the syntax for daily job Here it is opted
 * to execute at 06:00 AM everyday
 */
private static final String CRON_MARIADB_DUMP = "00 00 18 * * ?"; //$NON-NLS-1$

@Scheduled(cron = CRON_MARIADB_DUMP)
public boolean dbBackup(String dbName, String dbUserName, String dbPassword, String path, String date) {
    String executeCmd = "mysqldump -u " + dbUserName + " -p" + dbPassword + "--add-drop-database -B " + dbName + " -r " + path; //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
    Process process;
    try {
        System.out.println(executeCmd);// this out put works in mysql shell

        process = Runtime.getRuntime().exec(new String[] { "cmd.exe", "/c", executeCmd }); //$NON-NLS-1$//$NON-NLS-2$
        // process = Runtime.getRuntime().exec(executeCmd);
        int processComplete = process.waitFor();

        if (processComplete == 0) {
            System.out.println("Backup created successfully"); //$NON-NLS-1$
            return true;
        }
        System.out.println("Could not create the backup");//$NON-NLS-1$

    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return false;
}

public static void main(String[] args) {
    String date = new SimpleDateFormat("ddMMyyyy").format(new Date());// $NON-NLS-1$ //$NON-NLS-1$

    UtilityService us = new UtilityService();
    us.dbBackup("root", "root", "eboard", repo, date); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    System.out.println("Completed..."); //$NON-NLS-1$
}

}

this is the code, and when I run this, console printing like below..

mysqldump -u root -peboard--add-drop-database -B root -r "C:/DB_backup/dump-date.sql"
Could not create the backup
Completed...

Could be the permission issue of the ID you are using to talk with MySQL. However, you could dig deep if you add this --verbose in the mysqldump command. This enables the verbose mode and often helpful with the console logs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM