java使用Process对象可以对命令行进行命令输入
直接上代码
private void createExternalSubCompanyDatabase(String host, Integer port, String jdbcUsername, String jdbcPassword, String databaseName) {
boolean success = true;
try {
String command = mysqlPath + "/bin/mysql" +
" -h" + host +
" -P" + port +
" -u" + jdbcUsername +
" -p" + jdbcPassword +
" -e 'create database `" + databaseName + "` DEFAULT CHARACTER SET = `utf8mb4` DEFAULT COLLATE = `utf8mb4_general_ci`;'";
Process process = Runtime.getRuntime().exec(new String[]{
"sh",// 如果是windows系统则使用cmd
"-c",// 如果是windows系统则使用/c
command}
);
// 获取命令行交互的内容,process.getInputStream可获取正常反馈,process.getErrorStream只能获取错误反馈
BufferedReader inputBufferedReader = new BufferedReader(
new InputStreamReader(process.getErrorStream()));
// 如果错误反馈有内容,内容是警告而不是错误,则视为正常
String line;
while ((line = inputBufferedReader.readLine()) != null) {
if (!line.contains("[Warning]")) {
success = false;
}
}
// 等待命令执行结束
process.waitFor();
} catch (IOException | InterruptedException e) {
success = false;
log.error("外部服务器创建失败:", e);
}
if (!success) {
throw new ServiceException("创建数据库失败,请保证您已做到了以下几点:" +
"1. 请检查数据库连接是否正确 " +
"2. 用户名密码是否正确 " +
"3. 外部服务器是否允许远程访问 ");
}
}