springboot利用application.yml测试连接数据库
时间: 2023-09-04 19:15:55 浏览: 181
在 Spring Boot 中,我们可以使用 `application.yml` 文件来配置数据库连接信息。下面是一个示例:
```yaml
spring:
datasource:
url: jdbc:mysql://localhost:3306/testdb?useSSL=false&serverTimezone=UTC
username: root
password: password
driver-class-name: com.mysql.cj.jdbc.Driver
```
其中,`url` 是数据库的连接地址,`username` 和 `password` 是数据库的登录账号和密码,`driver-class-name` 是数据库驱动的类名。
接下来,我们可以编写一个简单的测试类来测试数据库连接。示例代码如下:
```java
@SpringBootTest
class DemoApplicationTests {
@Autowired
private DataSource dataSource;
@Test
void contextLoads() {
try (Connection conn = dataSource.getConnection()) {
System.out.println("连接成功!");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
在测试方法中,我们首先使用 `@Autowired` 注解注入 `DataSource` 对象,然后使用 `getConnection()` 方法来获取一个数据库连接,并打印出连接成功的信息。如果连接失败,就会打印出异常信息。
当我们运行测试方法时,如果一切正常,就会输出连接成功的信息。如果连接失败,就会输出异常信息。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)