[英]Execute SQL file from Spring JDBC Template
我正在尝试编写一些代码来读取 SQL 文件(多个CREATE TABLE
语句,由;
分隔)并执行所有语句。
在纯 JDBC 中,我可以这样写:
String sqlQuery = "CREATE TABLE A (...); CREATE TABLE B (...);"
java.sql.Connection connection = ...;
Statement statement = connection.createStatement();
statement.executeUpdate(sqlQuery);
statement.close();
并且两个(所有)语句都被执行了。 当我尝试在 spring JdbcTemplate 中做同样的事情时,虽然只执行了第一条语句!
String sqlQuery = "CREATE TABLE A (...); CREATE TABLE B (...);"
org.springframework.jdbc.core.JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.execute(sqlQuery);
有没有办法执行多条语句? 虽然谷歌上搜索,我发现只有像“由分裂的SQLQuery解决方案;
手动”这当然是无用的(它会需要更多的分析)。
也许 Spring 的ScriptUtils在你的情况下会很有用。 尤其是executeSqlScript
方法。
请注意, DEFAULT_STATEMENT_SEPARATOR
的默认值为';'
(请参阅常量字段值)
我已经通过这种方式解决了这个问题:
public void createDefaultDB(DataSource dataSource) {
Resource resource = new ClassPathResource("CreateDefaultDB.sql");
ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(resource);
databasePopulator.execute(dataSource);
}
您可以像往常一样注入DataSource
:
import javax.sql.DataSource;
//...
@Autowired
private DataSource dataSource;
尝试一下
public void executeSqlScript(Connection connection,StringBuffer sql)throws SQLException{
try {
connection.setAutoCommit(false);//disable auto commit
ScriptUtils.executeSqlScript(connection, new ByteArrayResource(sql.toString().getBytes()));
connection.commit();//commit manually
} catch (SQLException e) {
connection.rollback();
}finally{
connection.close();
}
}
我们也可以通过 SQLExec 来实现。 下面的代码对我有用。
导入 java.io.File;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.SQLExec;
public class Test {
public static void main(String[] args) {
Test t = new Test();
t.executeSql("");
}
private void executeSql(String sqlFilePath) {
final class SqlExecuter extends SQLExec {
public SqlExecuter() {
Project project = new Project();
project.init();
setProject(project);
setTaskType("sql");
setTaskName("sql");
}
}
SqlExecuter executer = new SqlExecuter();
executer.setSrc(new File("test1.sql"));
executer.setDriver("org.postgresql.Driver");
executer.setPassword("postgres");
executer.setUserid("postgres");
executer.setUrl("jdbc:postgresql://localhost/test");
executer.execute();
}
}
我正在为我的项目案例寻找类似的选项,然后我偶然发现了以下https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/jdbc/datasource/init/ ResourceDatabasePopulator.html
提供的 Stackoverflow 示例非常简洁,如果您希望 Spring 代表您处理样板 sql 处理https://stackoverflow.com/a/23036217/1958683
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.