天天看點

在java中調用指令行或終端連接配接資料庫并執行操作資料庫

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. 外部伺服器是否允許遠端通路 ");
    }
}