springboot操作数据库,只需要简单的几步即可实现:
上手体验:
1,新建项目导入starter
<!-- spring data-->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 数据库连接-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
2,application.yml配置数据源
由于数据库连接版本很高,url必须配置serverTimezone=UTC 不然会报错
spring:
datasource:
url: jdbc:mysql://localhost:3306/ssmbuild?serverTimezone=UTC
driver-class-name: com.mysql.jdbc.Driver
username: root
password: 1111
org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is 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.
当配置了数据源,springboot会自动装配,容器中提供数据源。当获得JdbcTemplate对象之后,直接可以进行数据操作,这中间获取连接都被容器接管。
package com.wang;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
import java.util.Map;
@SpringBootTest
class SpringbootDataApplicationTests {
@Autowired
private JdbcTemplate jdbcTemplate;
@Test
void contextLoads() {
jdbcTemplate.update("insert into books( bookName, bookCounts, detail)values('springboot',20,'好书')");
List list = jdbcTemplate.queryForList("select * from books");
for (Object item :list ) {
System.out.println(item);
}
}
}