java - 使用 Java 对 mysql 数据库进行简单备份和恢复

标签 java mysql database backup restore

如何从 java 代码备份 mysql 数据库:

  1. 它的保存路径是动态分配的。
  2. 路径中的空格不会产生问题。
  3. 路径是使用执行的 jar 文件生成的。
  4. DBname、DBusername 或 DBpass 是动态分配的。
  5. 创建专门的文件夹来保存备份文件。

最佳答案

注意:下面给出的代码是解决问题的一种方法,可能不是最好的方法。代码中的一切都是可变的。如果环境变量中没有mysql,则在mysqldump和mysql之前添加路径(例如对于XAMPP,C:\xampp\mysql\bin\mysqldump)

(希望,这会解决您的问题。我花了一天时间才完全弄清楚所有内容并正确实现)

备份方法:

public static void Backupdbtosql() {
    try {

        /*NOTE: Getting path to the Jar file being executed*/
        /*NOTE: YourImplementingClass-> replace with the class executing the code*/
        CodeSource codeSource = YourImplementingClass.class.getProtectionDomain().getCodeSource();
        File jarFile = new File(codeSource.getLocation().toURI().getPath());
        String jarDir = jarFile.getParentFile().getPath();


        /*NOTE: Creating Database Constraints*/
        String dbName = "YourDBName";
        String dbUser = "YourUserName";
        String dbPass = "YourUserPassword";

        /*NOTE: Creating Path Constraints for folder saving*/
        /*NOTE: Here the backup folder is created for saving inside it*/
        String folderPath = jarDir + "\\backup";

        /*NOTE: Creating Folder if it does not exist*/
        File f1 = new File(folderPath);
        f1.mkdir();

        /*NOTE: Creating Path Constraints for backup saving*/
        /*NOTE: Here the backup is saved in a folder called backup with the name backup.sql*/
         String savePath = "\"" + jarDir + "\\backup\\" + "backup.sql\"";

        /*NOTE: Used to create a cmd command*/
        String executeCmd = "mysqldump -u" + dbUser + " -p" + dbPass + " --database " + dbName + " -r " + savePath;

        /*NOTE: Executing the command here*/
        Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);
        int processComplete = runtimeProcess.waitFor();

        /*NOTE: processComplete=0 if correctly executed, will contain other values if not*/
        if (processComplete == 0) {
            System.out.println("Backup Complete");
        } else {
            System.out.println("Backup Failure");
        }

    } catch (URISyntaxException | IOException | InterruptedException ex) {
        JOptionPane.showMessageDialog(null, "Error at Backuprestore" + ex.getMessage());
    }
}

恢复方法:

public static void Restoredbfromsql(String s) {
        try {
            /*NOTE: String s is the mysql file name including the .sql in its name*/
            /*NOTE: Getting path to the Jar file being executed*/
            /*NOTE: YourImplementingClass-> replace with the class executing the code*/
            CodeSource codeSource = YourImplementingClass.class.getProtectionDomain().getCodeSource();
            File jarFile = new File(codeSource.getLocation().toURI().getPath());
            String jarDir = jarFile.getParentFile().getPath();

            /*NOTE: Creating Database Constraints*/
             String dbName = "YourDBName";
             String dbUser = "YourUserName";
             String dbPass = "YourUserPassword";

            /*NOTE: Creating Path Constraints for restoring*/
            String restorePath = jarDir + "\\backup" + "\\" + s;

            /*NOTE: Used to create a cmd command*/
            /*NOTE: Do not create a single large string, this will cause buffer locking, use string array*/
            String[] executeCmd = new String[]{"mysql", dbName, "-u" + dbUser, "-p" + dbPass, "-e", " source " + restorePath};

            /*NOTE: processComplete=0 if correctly executed, will contain other values if not*/
            Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);
            int processComplete = runtimeProcess.waitFor();

            /*NOTE: processComplete=0 if correctly executed, will contain other values if not*/
            if (processComplete == 0) {
                JOptionPane.showMessageDialog(null, "Successfully restored from SQL : " + s);
            } else {
                JOptionPane.showMessageDialog(null, "Error at restoring");
            }


        } catch (URISyntaxException | IOException | InterruptedException | HeadlessException ex) {
            JOptionPane.showMessageDialog(null, "Error at Restoredbfromsql" + ex.getMessage());
        }

    }

关于java - 使用 Java 对 mysql 数据库进行简单备份和恢复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14924770/

相关文章:

java - 在android中使用新数据刷新ListView

java - javac 足以构建 OSGi 包吗?

php - Htaccess 不适用于 Mamp

php - MySQL JOIN,通过 PHP,当其中一个表中没有数据时?

mysql - 如何修剪 MySQL 行中的前导和尾随引号?

android - 什么会导致使用 Android Studio 在 RoomDatabase 文件中不允许使用修改器 'abstract'?

java - Java 语言规范第 3 版勘误表

java - 无法在 Android Studio 上解析方法 setToNow()

Mysql加载数据infile忽略1行不起作用

MySQL服务器存储过程语法错误