在spring boot中执行一个Java脚本去MySQL数据库插入数据
时间: 2023-11-12 19:09:06 浏览: 242
可以通过在Spring Boot中使用JdbcTemplate或MyBatis等数据访问框架来执行SQL语句,从而向MySQL数据库插入数据。以下是一个使用JdbcTemplate的示例:
1. 首先,在pom.xml文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
```
2. 然后,在application.properties文件中配置MySQL数据库连接信息:
```properties
spring.datasource.url=jdbc:mysql://localhost:3306/testdb?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
```
3. 接着,创建一个Java类,使用JdbcTemplate执行SQL语句:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
@Component
public class DataInsertion {
@Autowired
private JdbcTemplate jdbcTemplate;
public void insertData() {
String sql = "INSERT INTO user(name, age) VALUES (?, ?)";
Object[] params = new Object[]{"Tom", 20};
jdbcTemplate.update(sql, params);
}
}
```
4. 最后,在Spring Boot的启动类中调用insertData方法:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
@Autowired
private DataInsertion dataInsertion;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
public void run(String... args) throws Exception {
dataInsertion.insertData();
}
}
```
这样,当运行Spring Boot应用程序时,就会执行insertData方法,向MySQL数据库插入一条数据。