我试图从我的Java应用程序(使用wamp服务器)备份mysql数据库但它不起作用,它始终显示消息“无法创建备份”。这是我从这个帖子中获取的代码:Backup a mysql [xampp] database in java
public static void saveBdd(){
String path = null;
String user = "root";
Process p = null;
JFileChooser fc = new JFileChooser();
fc.setDialogTitle("Choisir l'emplacement de la sauvegarde");
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.setAcceptAllFileFilterUsed(false);
fc.showOpenDialog(startPage);
String date = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
try {
File f = fc.getSelectedFile();
path = f.getAbsolutePath();
path = path.replace('\\', '/');
path = path+"/bcpbdd_"+date+".sql";
} catch (Exception e) {
e.printStackTrace();
}
try{
Runtime runtime = Runtime.getRuntime();
p=runtime.exec("C:/wamp64/bin/mysql/mysql5.7.23/bin/mysqldump -u " + user + " --add-drop-database -B bcpbdd -r "+path);
int processComplete = p.waitFor();
if (processComplete==0) {
StartPage.afficheMessage("Backup Created Success!");
} else {
StartPage.afficheMessage("Can't create backup.");
}
} catch (Exception e) {
StartPage.afficheMessage(e.getMessage());
}
}
您可以使用p.getErrorStream()
和p.getInputStream()
读取进程的输出。这应该在新的Thread中完成,然后您可以将输出写入日志文件或控制台。
这是我尝试和工作正常,
db_backup.sql
的任何路径。
Process rt = Runtime.getRuntime().exec("mysqldump -P 3306 -h 127.0.0.1 -u root test");
int exitCode = rt.waitFor();
System.out.println("Process exited with : " + exitCode);
BufferedReader in = new BufferedReader(new InputStreamReader(rt.getInputStream()));
BufferedReader err = new BufferedReader(new InputStreamReader(rt.getErrorStream()));
System.out.println("Backup file output:");
String line;
BufferedReader reader;
if (exitCode != 0) {
reader = err;
} else {
reader = in;
}
File file = new File("db_backup.sql");
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
while ((line = reader.readLine()) != null) {
System.out.println(line);
bufferedWriter.write(line);
bufferedWriter.newLine();
}
bufferedWriter.flush();
bufferedWriter.close();