springboot、连接数据库 ---JdbcTemplate

一、新建Maven工程,不全Maven所需文件夹,在pom.xml引入SpringBoot的依赖包!可以参照:http://www.cnblogs.com/liangblog/p/5207855.html

二、有两种方法与数据库建立连接,一种是集成Mybatis,另一种用JdbcTemplate


1.首先我们讲用JdbcTemplate连接,这个相对Mybatis来说是比较简单的

 导入依赖在maven的pom.xml

<dependency>
              <groupId>mysql</groupId>
              <artifactId>mysql-connector-java</artifactId>
          </dependency>
          <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

  

 添加配置文件配置数据库和其他参数

  在resource文件夹下添加application.properties配置文件并输入数据库参数,如下:

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=960512
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5

server.port=8080
#server.session.timeout=10
server.tomcat.uri-encoding=UTF-8

  



新建Controller类测试数据库连接

package com.SpringBoot.Test;

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 javax.swing.text.html.parser.Entity;
import java.util.List;
import java.util.Map;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;


/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Administrator
 * Date: 2018-12-16
 * Time: 22:28
 */
@RestController
public class SqlTest {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @RequestMapping("getUsers")
    public List<Map<String, Object>> getDbType(){
        String sql = "select * from student";
        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;
    }
}

 

 输入地址访问

 

 


 

posted @ 2018-12-17 21:56  IT路上的小白  阅读(160)  评论(0编辑  收藏  举报