文章转载于:https://blog.yoodb.com/yoodb/article/detail/1416
一、使用JdbcTemplate
1、在pom.xml中添加依赖:
<dependency> <!-- JDBC 数据库连接 --> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency>
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<Map<String, Object>> getDbType(){ String sql = "select * from emp"; 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; } }
4、运行项目:
① 访问:http://localhost:8012/mydb/getUsers ,输出所有信息:
控制台信息:
②访问http://localhost:8012/mydb/user/1 ,输出指定id的信息,但是有个问题,不管参数是多少,都只是显示第一个元素的信息,有待改正.