找到一篇很靠谱的帖子先贴出来
主要几个步骤
-
新建项目时添加依赖
就是pom.xml里的这两个,一定要导入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<!--<scope>runtime</scope>-->
</dependency>
application.properties中的配置,driverClassName使用com.mysql.jdbc.Driver运行时报错了
#数据库相关配置
spring.datasource.url = jdbc:mysql://127.0.0.1:3306/数据库名?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
spring.datasource.username = root
spring.datasource.password = 123
spring.datasource.driverClassName = com.mysql.cj.jdbc.Driver
可以通过下面的方式测试,可以读取到数据
@RestController
public class SQLTestController {
@Autowired
private JdbcTemplate jdbcTemplate;
@RequestMapping("/getUsers")
public List<Map<String, Object>> getDbType() {
String sql = "select * from test";
List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
for (Map<String, Object> map : list) {
Set<Map.Entry<String, Object>> entries = map.entrySet();
for (Map.Entry<String, Object> entry : entries) {
Object key = entry.getKey();
Object value = entry.getValue();
System.out.println(key + ":" + value);
}
}
return list;
}
}
但是这样的方式并不算容易,最方便的还是使用Mybatis