application.properties 配置好
spring.datasource.url=jdbc:mysql://localhost:3306/demo
spring.datasource.username=root
spring.datasource.password=
pom.xml 加上这俩
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
Main.java
@Slf4j
@Component
public class Main implements CommandLineRunner {
@Autowired
DataSource dataSource;
@Override
public void run(String... args) throws Exception {
val a = new FileSystemResource("a.sql");
val b = new FileSystemResource("b.sql");
val resourceDatabasePopulator = new ResourceDatabasePopulator();
resourceDatabasePopulator.addScripts(a, b);
resourceDatabasePopulator.execute(dataSource);
}
}
其中 a.sql b.sql 存在当前项目根目录
主要就是用 resourceDatabasePopulator 这个类
reference
https://stackoverflow.com/questions/30732314/execute-sql-file-from-spring-jdbc-template