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).
core. JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate. execute(sqlQuery);
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With