2016-05-26 14 views
1

プロシージャと挿入文を含むabc.sqlファイルがあります。スクリプトランナーAPIを使用せずにJavaコードを使用してスクリプト(abc.sqlファイル)を実行するにはどうすればよいですか。.sqlファイルを実行するJavaコードを使用する

+0

どのデータベースを使用していますか? –

+0

Oracle Database – Abby

+0

解決策が見つかりました。あなたはhttp://www.coderanch.com/t/306966/JDBC/databases/Execute-sql-file-javaから入手できます。 – ThanhLD

答えて

0

ProcessBuilderを使用してください。以下のサンプルコードでは、select queryを実行し、結果をコンソールに出力します。

public class RunOracleSql { 
    public static void main(String[] args) { 
     final String fileExtension = ".sql"; 
     String script_location = "C:/SQLFileLocation"; 
     try { 
      File file = new File("C:/SQLFileLocation"); 
      File[] listFiles = file.listFiles(new FileFilter() { 

       public boolean accept(File f) { 
        if (f.getName().toLowerCase().endsWith(fileExtension)) 
         return true; 
        return false; 
       } 
      }); 
      for (int i = 0; i < listFiles.length; i++) { 
       script_location = "@" + listFiles[i].getAbsolutePath();// ORACLE 
       ProcessBuilder processBuilder = new ProcessBuilder("sqlplus", 
         "username/[email protected]_name", script_location); // ORACLE 

       processBuilder.redirectErrorStream(true); 
       Process process = processBuilder.start(); 
       BufferedReader in = new BufferedReader(new InputStreamReader(
         process.getInputStream())); 
       String currentLine = null; 
       while ((currentLine = in.readLine()) != null) { 
        System.out.println(" " + currentLine); 
       } 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } catch (Exception ex) { 
      ex.printStackTrace(); 
     } 
    } 
} 
関連する問題