美文网首页
springboot连接mysql

springboot连接mysql

作者: 奋斗live | 来源:发表于2019-04-11 09:55 被阅读0次

    环境如下,对应的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

    相关文章

      网友评论

          本文标题:springboot连接mysql

          本文链接:https://www.haomeiwen.com/subject/ueuziqtx.html