Springboot连接数据库
# 数据库配置
spring:
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.jdbc.Driver
// 单元测试进行数据库连接测试
@Autowired
DataSource dataSource;
@Test
void contextLoads() throws SQLException {
// 查看默认的数据源 class com.zaxxer.hikari.HikariDataSource
System.out.println(dataSource.getClass());
// 获取数据库连接
Connection connection = dataSource.getConnection();
System.out.println(connection);
// 关闭连接
connection.close();
}
出现错误:java.sql.SQLException: The server time zone value ‘�й���ʱ��’ is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the ‘serverTimezone’ configuration property) to use a more specifc time zone value if you want to utilize time zone support.【时区报错】
原因:mysql-connector-java-8.0.20.jar:8.0.20 版本问题
解决办法:
# 数据库配置,添加:serverTimezone=UTC
spring:
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/mydb?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.jdbc.Driver
Springboot和Mybatis
- 整合spring和mybatis—>mybatis-spring
- 整合springboot和mybatis—>mybatis-spring-boot-starter