如何使用Java拆分sql查询

如何使用Java拆分sql查询,java,sql,sqlite,split,Java,Sql,Sqlite,Split,我播下了这些查询:查询在同一行上 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`, `upda

我播下了这些查询:查询在同一行上

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();

String[]parts=sql.split((?您可以使用“新行”符号分隔它们


可以使用“新线”符号将它们分开


可以使用“新线”符号将它们分开


可以使用“新线”符号将它们分开


您可以创建如下
SqlRunner
类并使用它; 详情请浏览 )

import java.io.IOException;
导入java.io.LineNumberReader;
导入java.io.PrintWriter;
导入java.io.Reader;
导入java.sql.Connection;
导入java.sql.ResultSet;
导入java.sql.ResultSetMetaData;
导入java.sql.SQLException;
导入java.sql.Statement;
导入java.util.regex.Matcher;
导入java.util.regex.Pattern;
导入org.apache.commons.lang.StringUtils;
公共类SqlRunner{
公共静态最终字符串分隔符_LINE_REGEX=“(?i)DELIMITER.+”,分隔符_LINE_SPLIT_REGEX=“(?i)DELIMITER”,默认值_DELIMITER=“;”;
私有最终布尔自动提交,stopOnError;
专用终端连接;
私有字符串分隔符=SqlRunner.DEFAULT_分隔符;
私人最终打印输出,错误;
公共SqlRunner(最终连接、最终打印输出、最终打印输出错误、最终布尔自动提交、最终布尔停止错误){
if(连接==null){
抛出新的RuntimeException(“SqlRunner需要SQL连接”);
}
if(err==null | | out==null){
抛出新的RuntimeException(“SqlRunner需要out和err printWriter”);
}
这个连接=连接;
this.autoCommit=自动提交;
this.stopOnError=stopOnError;
this.out=out;
this.err=err;
}
public void runScript(最终读取器)引发SQLException{
final boolean originalAutoCommit=this.connection.getAutoCommit();
试一试{
if(originalAutoCommit!=this.autoCommit){
this.connection.setAutoCommit(this.autoCommit);
}
this.runScript(this.connection,reader);
}最后{
this.connection.setAutoCommit(originalAutoCommit);
}
}
专用void运行脚本(最终连接连接,最终读卡器){
StringBuffer命令=null;
试一试{
最终LineNumberReader lineReader=新的LineNumberReader(读卡器);
字符串行=null;
而((line=lineReader.readLine())!=null){
如果(命令==null){
command=newstringbuffer();
}
String trimmedLine=line.trim();
if(trimmedLine.startsWith(“--”)trimmedLine.startsWith(“/”)| trimmedLine.startsWith(“#”){
//行是一个注释
out.println(trimmedLine);
out.flush();
}else if(trimmedLine.endsWith(this.delimiter)){
//行是语句的结尾
//支持新的分隔符
final Pattern=Pattern.compile(SqlRunner.DELIMITER\u LINE\u REGEX);
最终匹配器匹配器=pattern.Matcher(trimmedLine);
if(matcher.matches()){
delimiter=trimmedLine.split(SqlRunner.delimiter\u LINE\u split\u REGEX)[1].trim();
//已处理新分隔符,请继续下一步
//声明
line=lineReader.readLine();
如果(行==null){
打破
}
trimmedLine=line.trim();
}
//附加
append(line.substring(0,line.lastIndexOf(this.delimiter));
命令。追加(“”);
语句stmt=null;
结果集rs=null;
试一试{
stmt=conn.createStatement();
out.println();
out.println(命令);
out.flush();
布尔hasResults=false;
if(this.stopOnError){
hasResults=stmt.execute(command.toString());
}否则{
试一试{
stmt.execute(command.toString());
}捕获(最终SQLE异常){
e、 fillInStackTrace();
err.println(“命令错误:”+command);
错误println(e);
err.flush();
}
}
if(this.autoCommit&!conn.getAutoCommit()){
conn.commit();
}
rs=stmt.getResultSet();
if(hasResults&&rs!=null){
//打印结果列名
最终结果setMetadata md=rs.getMetaData();
final int cols=md.getColumnCount();
for(int i=0;i对于(inti=1;i您创建
SqlRunner
类如下并使用它; 详情请浏览 )

导入java
String[] parts = sql.split(System.lineSeparator());
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();
        }
    }
}