Aleksei Nikolaevich
Aleksei Nikolaevich

Reputation: 325

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 ?

Upvotes: 0

Views: 2720

Answers (2)

hrs
hrs

Reputation: 417

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.

Upvotes: 0

Turophile
Turophile

Reputation: 3405

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.

Upvotes: 2

Related Questions