Wednesday, July 7, 2021

Backup & Restore MySQL Database Using Java


import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public final class DatabaseUtil {

	public static boolean restore(String dbUsername, String dbPassword, String dbName, String sourceFile)
			throws IOException, InterruptedException {
		String[] command = new String[] { "mysql", "-u" + dbUsername, "-p" + dbPassword, "-e", " source " + sourceFile,
				dbName };

		Process runtimeProcess = Runtime.getRuntime().exec(command);
		int processComplete = runtimeProcess.waitFor();
		return processComplete == 0;
	}

	public static boolean tbBackup(String dbUsername, String dbPassword, String dbName, String outputFilePath) {

		DateFormat df = new SimpleDateFormat("ddMMMyyyy");
		String dat = df.format(new Date());
		outputFilePath = outputFilePath + dbName + dat + ".sql";
		String executeCmd = "mysqldump -u " + dbUsername + " -p" + dbPassword + " --add-drop-database -B " + dbName
				+ " -r " + outputFilePath;
		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;
	}
}

No comments:

Post a Comment