springboot连接mysql

2019-04-11  本文已影响0人  奋斗live

环境如下,对应的mysql数据


image.png
一、配置application.properties
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/security
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.max-idle=10
spring.datasource.max-wait=1000
spring.datasource.min-idle=5
spring.datasource.initial-size=5

如下图所示


image.png
二、编写controller
package com.example.rabbitmq.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

@RestController
public class IndexController {

    @Autowired
    private JdbcTemplate jdbcTemple;

    @RequestMapping("/index")
    public List<Map<String,Object>> index(){
        String sql = "SELECT * FROM users";
        List<Map<String,Object>> list = jdbcTemple.queryForList(sql);
        for(Map<String,Object> map:list){
            Set<Map.Entry<String,Object>> entries = map.entrySet();
            if(entries!=null){
                Iterator<Map.Entry<String,Object>> iterator = entries.iterator();
                while (iterator.hasNext()){
                    Map.Entry<String,Object> entry = iterator.next();
                    Object key = entry.getKey();
                    Object value = entry.getValue();
                    System.out.println(key+":"+value);
                }
            }
        }
        return list;
    }
}

三、测试

访问对应的url,即可输出数据,如下


image.png

对应的控制台输出数据


image.png
上一篇下一篇

猜你喜欢

热点阅读