注意:以下给出的代码是解决问题的一种方法,可能不是最佳方法。
代码中的所有内容都是可以更改的。如果环境变量中没有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()); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)