2017-04-04 22 views
-4

我有一個.SQL腳本文件,需要在執行一次完整的.sql文件,我發現有很多的相關答案,其中程序員閱讀文件,並通過一個執行查詢的一個。SCALA:執行完整的.sql文件

我要求所有在一次運行.sql文件,就像在撿文件,內SCALA執行英寸

目前我正在用下面的代碼複製它:https://gist.github.com/joe776/831762,我的Lead讓我用簡單的方式做,而不是逐行執行腳本,它應該被執行爲.SQL文件

import java.io.IOException; 
import java.io.LineNumberReader; 
import java.io.PrintWriter; 
import java.io.Reader; 
import java.sql.Connection; 
import java.sql.ResultSet; 
import java.sql.ResultSetMetaData; 
import java.sql.SQLException; 
import java.sql.Statement; 
import java.util.regex.Matcher; 
import java.util.regex.Pattern; 


public class ScriptRunner { 

    private static final String DEFAULT_DELIMITER = ";"; 
    private static final String DELIMITER_LINE_REGEX = "(?i)DELIMITER.+"; 
    private static final String DELIMITER_LINE_SPLIT_REGEX = "(?i)DELIMITER"; 

    private final Connection connection; 
    private final boolean stopOnError; 
    private final boolean autoCommit; 
    private PrintWriter logWriter = new PrintWriter(System.out); 
    private PrintWriter errorLogWriter = new PrintWriter(System.err); 
    private String delimiter = DEFAULT_DELIMITER; 
    private boolean fullLineDelimiter = false; 

    /** 
    * Default constructor. 
    * 
    * @param connection 
    * @param autoCommit 
    * @param stopOnError 
    */ 
    public ScriptRunner(Connection connection, boolean autoCommit, boolean stopOnError) { 
     this.connection = connection; 
     this.autoCommit = autoCommit; 
     this.stopOnError = stopOnError; 
    } 

    /** 
    * @param delimiter 
    * @param fullLineDelimiter 
    */ 
    public void setDelimiter(String delimiter, boolean fullLineDelimiter) { 
     this.delimiter = delimiter; 
     this.fullLineDelimiter = fullLineDelimiter; 
    } 

    /** 
    * Setter for logWriter property. 
    * 
    * @param logWriter 
    *  - the new value of the logWriter property 
    */ 
    public void setLogWriter(PrintWriter logWriter) { 
     this.logWriter = logWriter; 
    } 

    /** 
    * Setter for errorLogWriter property. 
    * 
    * @param errorLogWriter 
    *  - the new value of the errorLogWriter property 
    */ 
    public void setErrorLogWriter(PrintWriter errorLogWriter) { 
     this.errorLogWriter = errorLogWriter; 
    } 

    /** 
    * Runs an SQL script (read in using the Reader parameter). 
    * 
    * @param reader 
    *  - the source of the script 
    * @throws SQLException 
    *   if any SQL errors occur 
    * @throws IOException 
    *   if there is an error reading from the Reader 
    */ 
    public void runScript(Reader reader) throws IOException, SQLException { 
     try { 
      boolean originalAutoCommit = connection.getAutoCommit(); 
      try { 
       if (originalAutoCommit != autoCommit) { 
        connection.setAutoCommit(autoCommit); 
       } 
       runScript(connection, reader); 
      } finally { 
       connection.setAutoCommit(originalAutoCommit); 
      } 
     } catch (IOException e) { 
      throw e; 
     } catch (SQLException e) { 
      throw e; 
     } catch (Exception e) { 
      throw new RuntimeException("Error running script. Cause: " + e, e); 
     } 
    } 

    /** 
    * Runs an SQL script (read in using the Reader parameter) using the connection passed in. 
    * 
    * @param conn 
    *  - the connection to use for the script 
    * @param reader 
    *  - the source of the script 
    * @throws SQLException 
    *   if any SQL errors occur 
    * @throws IOException 
    *   if there is an error reading from the Reader 
    */ 
    private void runScript(Connection conn, Reader reader) throws IOException, SQLException { 
     StringBuffer command = null; 
     try { 
      LineNumberReader lineReader = new LineNumberReader(reader); 
      String line = null; 
      while ((line = lineReader.readLine()) != null) { 
       if (command == null) { 
        command = new StringBuffer(); 
       } 
       String trimmedLine = line.trim(); 
       if (trimmedLine.startsWith("--")) { 
        println(trimmedLine); 
       } else if (trimmedLine.length() < 1 || trimmedLine.startsWith("//")) { 
        // Do nothing 
       } else if (trimmedLine.length() < 1 || trimmedLine.startsWith("--")) { 
        // Do nothing 
       } else if (!fullLineDelimiter && trimmedLine.endsWith(getDelimiter()) 
         || fullLineDelimiter && trimmedLine.equals(getDelimiter())) { 

        Pattern pattern = Pattern.compile(DELIMITER_LINE_REGEX); 
        Matcher matcher = pattern.matcher(trimmedLine); 
        if (matcher.matches()) { 
         setDelimiter(trimmedLine.split(DELIMITER_LINE_SPLIT_REGEX)[1].trim(), 
           fullLineDelimiter); 
         line = lineReader.readLine(); 
         if (line == null) { 
          break; 
         } 
         trimmedLine = line.trim(); 
        } 

        command.append(line.substring(0, line.lastIndexOf(getDelimiter()))); 
        command.append(" "); 
        Statement statement = conn.createStatement(); 

        println(command); 

        boolean hasResults = false; 
        if (stopOnError) { 
         hasResults = statement.execute(command.toString()); 
        } else { 
         try { 
          statement.execute(command.toString()); 
         } catch (SQLException e) { 
          e.fillInStackTrace(); 
          printlnError("Error executing: " + command); 
          printlnError(e); 
         } 
        } 

        if (autoCommit && !conn.getAutoCommit()) { 
         conn.commit(); 
        } 

        ResultSet rs = statement.getResultSet(); 
        if (hasResults && rs != null) { 
         ResultSetMetaData md = rs.getMetaData(); 
         int cols = md.getColumnCount(); 
         for (int i = 0; i < cols; i++) { 
          String name = md.getColumnLabel(i); 
          print(name + "\t"); 
         } 
         println(""); 
         while (rs.next()) { 
          for (int i = 1; i <= cols; i++) { 
           String value = rs.getString(i); 
           print(value + "\t"); 
          } 
          println(""); 
         } 
        } 

        command = null; 
        try { 
         if (rs != null) { 
          rs.close(); 
         } 
        } catch (Exception e) { 
         e.printStackTrace(); 
        } 
        try { 
         if (statement != null) { 
          statement.close(); 
         } 
        } catch (Exception e) { 
         e.printStackTrace(); 
         // Ignore to workaround a bug in Jakarta DBCP 
        } 
       } else { 
        Pattern pattern = Pattern.compile(DELIMITER_LINE_REGEX); 
        Matcher matcher = pattern.matcher(trimmedLine); 
        if (matcher.matches()) { 
         setDelimiter(trimmedLine.split(DELIMITER_LINE_SPLIT_REGEX)[1].trim(), 
           fullLineDelimiter); 
         line = lineReader.readLine(); 
         if (line == null) { 
          break; 
         } 
         trimmedLine = line.trim(); 
        } 
        command.append(line); 
        command.append(" "); 
       } 
      } 
      if (!autoCommit) { 
       conn.commit(); 
      } 
     } catch (SQLException e) { 
      e.fillInStackTrace(); 
      printlnError("Error executing: " + command); 
      printlnError(e); 
      throw e; 
     } catch (IOException e) { 
      e.fillInStackTrace(); 
      printlnError("Error executing: " + command); 
      printlnError(e); 
      throw e; 
     } finally { 
      conn.rollback(); 
      flush(); 
     } 
    } 

    private String getDelimiter() { 
     return delimiter; 
    } 

    private void print(Object o) { 
     if (logWriter != null) { 
      logWriter.print(o); 
     } 
    } 

    private void println(Object o) { 
     if (logWriter != null) { 
      logWriter.println(o); 
     } 
    } 

    private void printlnError(Object o) { 
     if (errorLogWriter != null) { 
      errorLogWriter.println(o); 
     } 
    } 

    private void flush() { 
     if (logWriter != null) { 
      logWriter.flush(); 
     } 
     if (errorLogWriter != null) { 
      errorLogWriter.flush(); 
     } 
    } 
} 
+0

直接執行該命令,而你的問題是......? – Siyual

+0

更新問題@Siyual –

+1

請顯示您迄今爲止編寫的代碼。比如:打開文件,逐行閱讀。連接到數據庫,獲得連接。對於每行文本,執行該行文本給出的SQL語句。然後告訴我們什麼在您的代碼中不起作用。 – radumanolescu

回答

1

你爲什麼標籤 「斯卡拉」?
要同時執行整個SQL文件:
sql < myFile.sql

編輯:爲西里爾Corpet指出的那樣,你可以通過斯卡拉

import sys.process._ 
"sql < myfile.sql" ! 
+0

那麼一次執行.sql文件,我與scalatest工作,有實際的測試,其中涉及之前運行安裝程序執行.sql文件,不能隨便運行手動每次 –

+0

無需手工做:'進口sys.process._「SQL