1.主程序中添加代码,执行sql脚本
Spring 中提供了一个 jdbc 脚本执行器,使用这个工具可以非常方便的运行一个 sql 脚本文件,下面是这个方法:
ScriptUtils.executeSqlScript()
只需要传入它需要的参数即可。
下面代码运行 sql 目录中的四个脚本程序,每次运行都会删除四个数据库再重新创建,并初始化数据。
package cn.tedu.dbinit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.jdbc.datasource.init.ScriptUtils;
import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.sql.SQLException;
@SpringBootApplication
public class DbInitApplication {
@Autowired
private DataSource dataSource;
public static void main(String[] args) {
SpringApplication.run(DbInitApplication.class, args);
}
@PostConstruct
public void init() throws SQLException {
exec(dataSource, "sql/account.sql");
exec(dataSource, "sql/storage.sql");
exec(dataSource, "sql/order.sql");
exec(dataSource, "sql/seata-server.sql");
}
private void exec(DataSource accountDatasource, String script) throws SQLException {
ClassPathResource rc = new ClassPathResource(script, DbInitApplication.class.getClassLoader());
EncodedResource er = new EncodedResource(rc, "utf-8");
ScriptUtils.executeSqlScript(accountDatasource.getConnection(), er);
}
}