从Spring JDBC模板执行SQL文件 [英] Execute SQL file from Spring JDBC Template
问题描述
我正在尝试编写一些代码来读取SQL文件(多个CREATE TABLE
语句,用;
分隔)并执行所有语句.
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.
在纯JDBC中,我可以写:
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();
和两个(所有)语句均已执行.当我尝试在春季JdbcTemplate中执行相同的操作时,虽然只执行了第一条语句!
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);
是否可以执行多个语句?在进行谷歌搜索时,我发现只有通过;
手动分割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).
推荐答案
Maybe Spring's ScriptUtils will be useful in your case. Especially executeSqlScript
methods.
请注意,DEFAULT_STATEMENT_SEPARATOR
的默认值为';'
(请参阅
Note that DEFAULT_STATEMENT_SEPARATOR
has a default value of ';'
(see Constant Field Values)
这篇关于从Spring JDBC模板执行SQL文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!