2014-09-30 174 views
0

我播种了这些查询:查询在同一行上。如何使用Java拆分sql查询

INSERT INTO data_location (`latitude`, `updated`, `id`, `longitude`, `created`) 
VALUES('213.2000000', '2014-08-25 11:07:42+00:00', '1', '321.0000000', 
    '2014-08-25 11:07:42+00:00'); 
INSERT INTO data_location (`latitude`, `updated`, `id`, `longitude`, `created`) 
VALUES('42.7191000', '2014-09-17 12:53:49+00:00', '2', '23.0834000', 
    '2014-09-17 12:53:49+00:00'); 
INSERT INTO data_news (`id`, `title`, `date`, `short_content`, `content`, 
    `created`, `updated`) 
VALUES(10, 'fdsafsda.', 'fdsafafa>', '2014-09-26 08:10:55', '2014-09-26 08:10:55'); 
INSERT INTO data_news (`id`, `title`, `date`, `short_content`, `content`, 
    `created`, `updated`) 
VALUES(11, 'fdsafdsafd „THE THROWAWAYS”', '2014-09-26 11:22:00', 
    'fdsafdsafdsafda(dsa);', '2014-09-26 09:05:09', '2014-09-26 09:05:09'); 

我想分开它们。在这个阶段,用下面的方法来划分他们:

String[] parts = sql.split("(?<=\\);)"); 
db.beginTransaction(); 
for (String entry : parts) { 
    SQLiteStatement stmt = db.compileStatement(entry); 
    stmt.execute(); 
    stmt.clearBindings(); 
} 
db.setTransactionSuccessful(); 
db.endTransaction(); 

的问题是,在过去的查询数据具有以下...safda(dsa);...它被接受,并成为无效的查询。有没有办法分裂聪明不接受这样的问题?

+0

我固定的报价。 – Krasimir 2014-09-30 11:58:44

回答

0

您可以使用“新行”符号将它们分开。

String[] parts = sql.split(System.lineSeparator()); 
+0

这一切都在一行 – Krasimir 2014-09-30 11:50:38

1

创建SqlRunner类作为遵循和使用它; 查看详情 http://allstarnix.blogspot.com.tr/2013/03/how-to-execute-sql-script-file-using.html;

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; 

import org.apache.commons.lang.StringUtils; 

public class SqlRunner { 
    public static final String DELIMITER_LINE_REGEX = "(?i)DELIMITER.+", DELIMITER_LINE_SPLIT_REGEX = "(?i)DELIMITER", DEFAULT_DELIMITER = ";"; 
    private final boolean autoCommit, stopOnError; 
    private final Connection connection; 
    private String delimiter = SqlRunner.DEFAULT_DELIMITER; 
    private final PrintWriter out, err; 

    public SqlRunner(final Connection connection, final PrintWriter out, final PrintWriter err, final boolean autoCommit, final boolean stopOnError) { 
     if (connection == null) { 
      throw new RuntimeException("SqlRunner requires an SQL Connection"); 
     } 
     if (err == null || out == null) { 
      throw new RuntimeException("SqlRunner requires both out and err PrintWriters"); 
     } 
     this.connection = connection; 
     this.autoCommit = autoCommit; 
     this.stopOnError = stopOnError; 
     this.out = out; 
     this.err = err; 
    } 

    public void runScript(final Reader reader) throws SQLException { 
     final boolean originalAutoCommit = this.connection.getAutoCommit(); 
     try { 
      if (originalAutoCommit != this.autoCommit) { 
       this.connection.setAutoCommit(this.autoCommit); 
      } 
      this.runScript(this.connection, reader); 
     } finally { 
      this.connection.setAutoCommit(originalAutoCommit); 
     } 
    } 

    private void runScript(final Connection conn, final Reader reader) { 
     StringBuffer command = null; 
     try { 
      final 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("--") || trimmedLine.startsWith("//") || trimmedLine.startsWith("#")) { 

        // Line is a comment 
        out.println(trimmedLine); 
        out.flush(); 

       } else if (trimmedLine.endsWith(this.delimiter)) { 

        // Line is end of statement 

        // Support new delimiter 
        final Pattern pattern = Pattern.compile(SqlRunner.DELIMITER_LINE_REGEX); 
        final Matcher matcher = pattern.matcher(trimmedLine); 
        if (matcher.matches()) { 
         delimiter = trimmedLine.split(SqlRunner.DELIMITER_LINE_SPLIT_REGEX)[1].trim(); 

         // New delimiter is processed, continue on next 
         // statement 
         line = lineReader.readLine(); 
         if (line == null) { 
          break; 
         } 
         trimmedLine = line.trim(); 
        } 

        // Append 
        command.append(line.substring(0, line.lastIndexOf(this.delimiter))); 
        command.append(" "); 

        Statement stmt = null; 
        ResultSet rs = null; 
        try { 
         stmt = conn.createStatement(); 
         out.println(); 
         out.println(command); 
         out.flush(); 
         boolean hasResults = false; 
         if (this.stopOnError) { 
          hasResults = stmt.execute(command.toString()); 
         } else { 
          try { 
           stmt.execute(command.toString()); 
          } catch (final SQLException e) { 
           e.fillInStackTrace(); 
           err.println("Error on command: " + command); 
           err.println(e); 
           err.flush(); 
          } 
         } 
         if (this.autoCommit && !conn.getAutoCommit()) { 
          conn.commit(); 
         } 
         rs = stmt.getResultSet(); 
         if (hasResults && rs != null) { 

          // Print result column names 
          final ResultSetMetaData md = rs.getMetaData(); 
          final int cols = md.getColumnCount(); 
          for (int i = 0; i < cols; i++) { 
           final String name = md.getColumnLabel(i + 1); 
           out.print(name + "\t"); 
          } 
          out.println(""); 
          out.println(StringUtils.repeat("---------", md.getColumnCount())); 
          out.flush(); 

          // Print result rows 
          while (rs.next()) { 
           for (int i = 1; i <= cols; i++) { 
            final String value = rs.getString(i); 
            out.print(value + "\t"); 
           } 
           out.println(""); 
          } 
          out.flush(); 
         } else { 
          out.println("Updated: " + stmt.getUpdateCount()); 
          out.flush(); 
         } 
         command = null; 
        } finally { 
         if (rs != null) 
          try { 
           rs.close(); 
          } catch (final Exception e) { 
           err.println("Failed to close result: " + e.getMessage()); 
           err.flush(); 
          } 
         if (stmt != null) 
          try { 
           stmt.close(); 
          } catch (final Exception e) { 
           err.println("Failed to close statement: " + e.getMessage()); 
           err.flush(); 
          } 
        } 
       } else { 

        // Line is middle of a statement 

        // Support new delimiter 
        final Pattern pattern = Pattern.compile(SqlRunner.DELIMITER_LINE_REGEX); 
        final Matcher matcher = pattern.matcher(trimmedLine); 
        if (matcher.matches()) { 
         delimiter = trimmedLine.split(SqlRunner.DELIMITER_LINE_SPLIT_REGEX)[1].trim(); 
         line = lineReader.readLine(); 
         if (line == null) { 
          break; 
         } 
         trimmedLine = line.trim(); 
        } 
        command.append(line); 
        command.append(" "); 
       } 
      } 
      if (!this.autoCommit) { 
       conn.commit(); 
      } 
     } catch (final SQLException e) { 
      e.fillInStackTrace(); 
      err.println("Error on command: " + command); 
      err.println(e); 
      err.flush(); 
     } catch (final IOException e) { 
      e.fillInStackTrace(); 
      err.println("Error on command: " + command); 
      err.println(e); 
      err.flush(); 
     } 
    } 
} 
+1

我认为有一个简单的方法作为正则表达式,而不是让类来解决这个问题。 – Krasimir 2014-09-30 11:57:57

+0

好的,但有时正则表达式解决方案变得更加复杂,我认为一个明显的解决方案更简单。 – dursun 2014-09-30 12:07:19

+0

当脚本包含一个'DECLARE @ variable'(Transact-sql) – Venom 2016-07-19 15:30:22

0

如果您的样本数据中显示所有角落的情况下,你需要找到的是所有;后面没有'。这将与正则表达式;[^']一起使用。 因此,拆分命令将是:String[] parts = sql.split(";[^']"); 在我的测试中,这给每个行一个SQL查询。

2

如果所有的查询,看起来像这些的在你的榜样,那么你可以在结束与收盘parenthes匹配,太:');

所以分割变为:sql.split("(?<='\\);)");