springboot怎么连接数据库
时间: 2023-10-17 11:05:49 浏览: 23
连接数据库需要进行以下步骤:
1. 在 `pom.xml` 文件中添加对应的数据库驱动依赖,例如 MySQL 的依赖:
```
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.22</version>
</dependency>
```
2. 在 `application.properties` 或 `application.yml` 中添加数据库的配置信息,例如 MySQL 的配置:
```
spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
```
3. 在代码中使用 `JdbcTemplate` 或者其他 ORM 框架进行数据库操作,例如使用 `JdbcTemplate` 进行查询:
```
@Autowired
private JdbcTemplate jdbcTemplate;
public List<String> getAllNames() {
return jdbcTemplate.queryForList("SELECT name FROM mytable", String.class);
}
```
以上就是连接数据库的简单步骤,具体的配置和使用需要根据具体的需求进行调整。