='20180201' AND date<='20180228'" -uuser --6ren">
gpt4 book ai didi

带有where选项的java mysqldump

转载 作者:太空宇宙 更新时间:2023-11-04 10:06:58 25 4
gpt4 key购买 nike

我尝试使用这段代码,它在 java 下的 linux 命令行上运行

mysqldump --where="date>='20180201' AND date<='20180228'" -uuser -ppassword --skip-add-drop-table --no-create-info --no-create-db -B mydb --tables table1 -r /root/Documents/DbBackup/table1.sql

为了让它在 java 中工作,我使用了以下代码:

public static boolean backupDB(String dbName, String where_filter, String path, String tableName) {
String executeCmd = "mysqldump --where="+where_filter+" -u" + userName + " -p" + password + " --skip-add-drop-table --no-create-info --no-create-db "+" -B " + dbName +" "+tableName+" -r " + path;

System.out.println("backupDB "+executeCmd);
Process runtimeProcess;
try {

runtimeProcess = Runtime.getRuntime().exec(executeCmd);
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) {

}

return false;
}

如果调用在 java 代码中,则相同的命令行指令不起作用。我哪里错了?是否可以将错误日志重定向到文件?

如果我使用 as where 子句 --where=date='20180206'它也适用于 java。

最佳答案

命令中的参数太多。我认为您应该使用 ProcessBuilder 而不是 Runtime.exec。它将命令和参数作为一个数组,恕我直言,这种方式更安全。所以试试这个代码:

String[] executeCmd = new String[]{
"mysqldump", "--where=" + where_filter, "-u" + userName, "-p" + password,
"--skip-add-drop-table", "--no-create-info", "--no-create-db", "-B", dbName,
"--tables", tableName, "--result-file=" + path
};
ProcessBuilder builder = new ProcessBuilder(executeCmd);
builder.redirectErrorStream(true);
Process runtimeProcess;
try {

runtimeProcess = builder.start();
InputStream processInputStream = process.getInputStream();
int processComplete = runtimeProcess.waitFor();
if (processComplete == 0) {
System.out.println("Backup created successfully");
return true;
} else {
System.out.println("Could not create the backup");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(processInputStream));
System.out.println("output: ");
while (reader.ready()) {
System.out.println(reader.readLine());
}
} catch (Exception ex) {

}
return false;

同时尝试使用像 /usr/bin/mysqldump 这样的完整路径编写 mysqldump 命令,如果可以的话,那么 mysqldump 命令不在路径中。

关于带有where选项的java mysqldump,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51874908/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com