简体   繁体   中英

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="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

It is very cumbersome to split my query into multiple 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.

Here a starting point: 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

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.

It shouldn't be cumbersome, you've already done it by having your query containing the ; character, which naturally terminates a SQL query.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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