Execute SQL file from Spring JDBC Template

后端 未结 4 921
我在风中等你
我在风中等你 2021-02-05 06:44

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

相关标签:
4条回答
  • 2021-02-05 07:21

    try it

    public void executeSqlScript(Connection connection,StringBuffer sql)throws SQLException{
             try {
                 connection.setAutoCommit(false);//设置为手工提交模式  
                 ScriptUtils.executeSqlScript(connection, new ByteArrayResource(sql.toString().getBytes()));
                 connection.commit();//提交事务  
            } catch (SQLException e) {
                connection.rollback();
            }finally{
                connection.close();
            }
         }
    
    0 讨论(0)
  • 2021-02-05 07:34

    We can also achive through SQLExec. Below code is working for me.

    import 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();
        }
    }
    
    0 讨论(0)
  • 2021-02-05 07:36

    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)

    0 讨论(0)
  • 2021-02-05 07:43

    I've solved the issue this way:

    public void createDefaultDB(DataSource dataSource) {
        Resource resource = new ClassPathResource("CreateDefaultDB.sql");
        ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(resource);
        databasePopulator.execute(dataSource);
    }
    

    You can inject DataSource as usual:

    import javax.sql.DataSource;
    //...
    @Autowired
    private DataSource dataSource;
    
    0 讨论(0)
提交回复
热议问题