从Java轻松备份和还原mysql数据库

从Java轻松备份和还原mysql数据库,第1张

从Java轻松备份还原mysql数据库

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

(希望能解决您的问题。花了我一天的时间完全弄清一切并正确实施)

备份方法:

public static void Backupdbtosql() {    try {                        CodeSource preSource = YourImplementingClass.class.getProtectionDomain().getCodeSource();        File jarFile = new File(preSource.getLocation().toURI().getPath());        String jarDir = jarFile.getParentFile().getPath();                String dbName = "YourDBName";        String dbUser = "YourUserName";        String dbPass = "YourUserPassword";                        String folderPath = jarDir + "\backup";                File f1 = new File(folderPath);        f1.mkdir();                         String savePath = """ + jarDir + "\backup\" + "backup.sql"";                String executeCmd = "mysqldump -u" + dbUser + " -p" + dbPass + " --database " + dbName + " -r " + savePath;                Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);        int processComplete = runtimeProcess.waitFor();                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 {    CodeSource preSource = YourImplementingClass.class.getProtectionDomain().getCodeSource(); File jarFile = new File(preSource.getLocation().toURI().getPath()); String jarDir = jarFile.getParentFile().getPath();   String dbName = "YourDBName";  String dbUser = "YourUserName";  String dbPass = "YourUserPassword";  String restorePath = jarDir + "\backup" + "\" + s;   String[] executeCmd = new String[]{"mysql", dbName, "-u" + dbUser, "-p" + dbPass, "-e", " source " + restorePath};  Process runtimeProcess = Runtime.getRuntime().exec(executeCmd); int processComplete = runtimeProcess.waitFor();  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());        }    }


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5587134.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-14
下一篇 2022-12-14

发表评论

登录后才能评论

评论列表(0条)

保存