Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute SQL file from Spring JDBC Template

Tags:

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).

like image 374
Ondrej Skalicka Avatar asked Jun 09 '15 12:06

Ondrej Skalicka


People also ask

How do I run a SQL file in JdbcTemplate?

core. JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate. execute(sqlQuery);

How do you run a query using JdbcTemplate Spring boot?

Configure JdbcTemplateUnder the com/twilio/jdbcTemplate create a package named config. Right click on the config package and create a new class named AppConfig which you will use to configure JdbcTemplate . The @Configuration annotation indicates that this class will hold a collection of beans for our application.

How do you fetch the records from the database using JDBC template class?

Here in getDatasource() method we create a new Datasource and configure it. Create a new JdbcTemplate object, with the given datasource to obtain connections from. Use the queryForList(String sql) API method of JdbcTemplate class to execute a query for a result list, with the given static SQL select query.


1 Answers

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)

like image 182
siphiuel Avatar answered Sep 30 '22 14:09

siphiuel