一、使用JdbcTemplate
1、在pom.xml中添加依赖:
mysql
mysql-connector-java
org.springframework.boot
spring-boot-starter-jdbc
2、在src/main/resource文件夹下的application.properties文件中填写数据库配置信息:spring.datasource.url=jdbc:mysql://127.0.0.1:3306/emp //数据库名
spring.datasource.username=root
spring.datasource.password=root //密码
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.max-idle=10
spring.datasource.max-wait=1000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
server.port=8012 //注意这里的端口
server.session.timeout=10
server.tomcat.uri-encoding=UTF-8
3、在src/main/java文件夹下新建类文件:package com.example.demo;
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 DBController {
@Autowired
private JdbcTemplate jdbcTemplate;
@RequestMapping("/getUsers")//访问路径:/mydb/getUsers
public List> getDbType(){
String sql = "select * from emp";
List> list = jdbcTemplate.queryForList(sql);
for (Map map : list) {
Set> entries = map.entrySet( );
if(entries != null) {
Iterator> iterator = entries.iterator( );
while(iterator.hasNext( )) {
Entry entry =(Entry) iterator.next( );
Object key = entry.getKey();
Object value = entry.getValue();
System.out.println(key+":"+value);
}
}
}
return list;
}
@RequestMapping("/user/{id}")
public Map getUser(@PathVariable String id){
Map map = null;
List> list = getDbType();
for (Map dbmap : list) {
Set 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;
}
}
4、运行项目:
控制台信息:
②访问http://localhost:8012/mydb/user/1 ,输出指定id的信息,但是有个问题,不管参数是多少,都只是显示第一个元素的信息,有待改正.