1.添加数据库依赖
<version>5.1.40</version> 这个版本号如果不加上会报:Cannot load JDBC driver class 'com.mysql.jdbc.Driver"的错误
<!--mysql 驱动-->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
<!--支持jdbc-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
2.在resource文件夹下 application.properties 配置文件并输入数据库参数
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test_book
spring.datasource.username=root
spring.datasource.password=123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
3.新建Controller类测试数据库连接
package com.example.demo.controller;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/mydb")
public class mysqlcontrol {
@Autowired
private JdbcTemplate jdbcTemplate;
@RequestMapping("/books")
public List<Map<String, Object>> getDbType(){
String sql = "select * from book";
List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
for (Map<String, Object> map : list) {
Set<Entry<String, Object>> entries = map.entrySet( );
if(entries != null) {
Iterator<Entry<String, Object>> iterator = entries.iterator( );
while(iterator.hasNext( )) {
Entry<String, Object> entry =(Entry<String, Object>) iterator.next( );
Object key = entry.getKey( );
Object value = entry.getValue();
System.out.println(key+":"+value);
}
}
}
return list;
}
@RequestMapping("/user/{id}")
public Map<String,Object> getUser(@PathVariable String id){
Map<String,Object> map = null;
List<Map<String, Object>> list = getDbType();
for (Map<String, Object> dbmap : list) {
Set<String> set = dbmap.keySet();
for (String key : set) {
if(key.equals("id")){
if(dbmap.get(key).equals(id)){
map = dbmap;
}
}
}
}
if(map==null)
map = list.get(0);
return map;
}
}