我想在mysql 5.6中备份数据库 为此,我使用这种方法:
public boolean backupDB(String dbName, String dbUserName, String dbPassword, String path) {
String executeCmd = "D://mysql-5.6.11-win32/bin/mysqldump -u " + dbUserName + " -p" + dbPassword
+ " --add-drop-database -B " + dbName + " -r " + path;
Process runtimeProcess;
try {
runtimeProcess = Runtime.getRuntime().exec(executeCmd);
// any error message?
StreamGobbler errorGobbler = new StreamGobbler(runtimeProcess.getErrorStream(), "ERR");
// any output?
StreamGobbler outputGobbler = new StreamGobbler(runtimeProcess.getInputStream(), "OUT");
// kick them off
errorGobbler.start();
outputGobbler.start();
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;
}
StreamGobbler是将runtimeProcess.getErrorStream()
和runtimeProcess.getInputStream()
包装到BufferedReader中的线程。 BufferedReader仅使用readLine()
方法逐行读取。这是我this article的提示。
我的问题是方法backupDB挂起在这一行:
int processComplete = runtimeProcess.waitFor();
如果我用exitValue替换waitFor方法,我收到错误
java.lang.IllegalThreadStateException: process has not exited
因此我必须使用waitFor方法。不幸的是它永远运行。我必须在eclipse控制台上按红色图标才能停止JVM。
如何使进程完成并备份mysql数据库? 这解决了谢谢!
编辑要启动mysqldump.exe,我需要编写完整路径:
String executeCmd = "D://mysql-5.6.11-win32/bin/mysqldump -u "
难道你不知道如何摆脱完整的道路。我想在计算机上的mysqldump.exe位置独立启动mysqldump。
也许有办法让mysqldump.exe的路径具有所有连接细节。
编辑如果我尝试使用没有mysqldump.exe完整路径的mysqldump,我会收到此异常:
java.io.IOException: Cannot run program "mysqldump": CreateProcess error=2, Íå óäàåòñÿ íàéòè óêàçàííûé ôàéë
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
at java.lang.Runtime.exec(Runtime.java:615)
at java.lang.Runtime.exec(Runtime.java:448)
at java.lang.Runtime.exec(Runtime.java:345)
at dbViewer.model.ConnectionManager.backupDB(ConnectionManager.java:273)
at dbViewer.model.ConnectionManager.main(ConnectionManager.java:337)
Caused by: java.io.IOException: CreateProcess error=2, Íå óäàåòñÿ íàéòè óêàçàííûé ôàéë
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(ProcessImpl.java:189)
at java.lang.ProcessImpl.start(ProcessImpl.java:133)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1021)
... 5 more
谢谢!
答案 0 :(得分:2)
您只需使用mysqldump -p 选项:
mysqldump –u[user name] –p[password] [database name] > [dump file]