从 Spring JDBC 模板执行 SQL 文件

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

有没有办法执行多条语句?在谷歌搜索时,我只找到了 "split the sqlQuery by ; manually" 这样的解决方案,这当然是无用的(它需要更多的解析)。

也许 Spring 的 ScriptUtils 对您有用。特别是 executeSqlScript 方法。

请注意 DEFAULT_STATEMENT_SEPARATOR 的默认值为 ';'(参见 Constant Field Values

我是这样解决问题的:

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;

我们也可以通过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();
    }
}

试一试

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();
        }
     }

我正在为我的项目案例寻找类似的选项,然后我偶然发现了以下 https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/jdbc/datasource/init/ResourceDatabasePopulator.html

提供的 Whosebug 示例非常简洁,如果您希望 Spring 代表您处理样板 sql