Java – Execute SQL file from Spring JDBC Template

javajdbctemplatespring

I'm trying to write a bit of code that reads a SQL file (multiple CREATE TABLE statements separated by ;) and executes all the statements.

In pure JDBC, I could write:

String sqlQuery = "CREATE TABLE A (...); CREATE TABLE B (...);"
java.sql.Connection connection = ...;
Statement statement = connection.createStatement();
statement.executeUpdate(sqlQuery);
statement.close();

and both (all) the statements got executed. When I tried to do the same in spring JdbcTemplate, only the first statement is executed though!

String sqlQuery = "CREATE TABLE A (...); CREATE TABLE B (...);"
org.springframework.jdbc.core.JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.execute(sqlQuery);

Is there a way to execute multiple statements? While googling I found only solutions like "split the sqlQuery by ; manually" which of course is useless (it'd require much more parsing).

Best Solution

Maybe Spring's ScriptUtils will be useful in your case. Especially executeSqlScript methods.

Note that DEFAULT_STATEMENT_SEPARATOR has a default value of ';' (see Constant Field Values)