简体   繁体   English

如何将多个语句的查询作为一个执行?

[英]How to execute query of multiple statements as one?

I came around an obstacle . 我遇到了一个障碍。 The following statement does not execute because the String query contains multiple statements . 以下语句不会执行,因为String query包含多个语句。

String query="create volatile table test1 as (etc . ); select TOP 10 * from test1; ";

        String driver = "com.xxx";
        String conUrl="jdbc:ccc";
        Class.forName(driver);
        Connection conn = DriverManager.getConnection(conUrl,user,password);

        PreparedStatement stmt=conn.prepareStatement(query);

The last line throws an error Data definition not valid unless solitary 最后一行抛出错误Data definition not valid unless solitary

It is very cumbersome to split my query into multiple PreparedStatements 将查询拆分为多个PreparedStatements非常麻烦

Is there any other way to execute a query containing multiple statements as one ? 有没有其他方法来执行包含多个语句的查询作为一个?

You could use JDBC batch processing (addBatch, executeBatch), which allows you to "stack" statements and send them all to the db engine to be executed at once. 您可以使用JDBC批处理(addBatch,executeBatch),它允许您“堆栈”语句并将它们全部发送到db引擎以立即执行。

Here a starting point: http://viralpatel.net/blogs/batch-insert-in-java-jdbc/ 这是一个起点: http//viralpatel.net/blogs/batch-insert-in-java-jdbc/

But you would still need to split it up into separate statements, and add them one at a time. 但是您仍然需要将其拆分为单独的语句,并一次添加一个。 Java: splitting a comma-separated string but ignoring commas in quotes Java:拆分以逗号分隔的字符串,但忽略引号中的逗号

And, as @CHEBURASHKA has pointed out, it only returns the number of rows affected by each statement - no good if you want to ask for actual data from the tables. 而且,正如@CHEBURASHKA指出的那样,它只返回受每个语句影响的行数 - 如果你想从表中请求实际数据,那就不好了。

It shouldn't be cumbersome, you've already done it by having your query containing the ; 它不应该是繁琐的,你已经通过让你的查询包含; character, which naturally terminates a SQL query. 字符,自然终止SQL查询。

So you have to do: 所以你必须这样做:

Stream.of(query.split(";")).forEach(sqlStatement -> System.out.println(sqlStatement))

Just replace the println for whatever mechanism you use to execute the sql query. 只需将println替换为用于执行sql查询的任何机制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM