Java连接mysql并且用map_springboot使用jdbc连接mysql数据库

连接配置参考:

https://www.cnblogs.com/liangblog/p/5228548.html

其中报错参考:

https://my.oschina.net/gef/blog/712383

下面摘抄:

一、添加依赖

mysql

mysql-connector-java

org.springframework.boot

spring-boot-starter-jdbc

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

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

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test

spring.datasource.username=root

spring.datasource.password=123456

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=8011

server.servlet.session.timeout=10

server.tomcat.uri-encoding=UTF-8

三、新建Controller类测试数据库连接在(DbController.java)

package com.lgp.SpringBoot;

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")

public List> getDbType(){

String sql = "select * from appuser";

List> list = jdbcTemplate.queryForList(sql);

for (Mapmap : list) {

Set> entries = map.entrySet( );

if(entries != null) {

Iterator> iterator = entries.iterator( );

while(iterator.hasNext( )) {

Entryentry =(Entry) iterator.next( );

Object key = entry.getKey( );

Object value = entry.getValue();

System.out.println(key+":"+value);

}

}

}

return list;

}

@RequestMapping("/user/{id}")

public MapgetUser(@PathVariable String id){

Mapmap = null;

List> list = getDbType();

for (Mapdbmap : list) {

Setset = 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;

}

}

四、运行App 输入地址 输出数据库数据。。。。。。

五、会报错

解决办法:

jdbcUrl=jdbc:mysql://localhost:3306/spring

后面加上:

jdbcUrl=jdbc:mysql://localhost:3306/spring?serverTimezone=UTC

但如果你的jdbcUrl类似下面:

jdbcUrl=jdbc:mysql://localhost:3306/spring?serverTimezone=UTC&characterEncoding=utf-8

就是有多个params的时候需要以&分开,但&要改为& 如下:

jdbcUrl=jdbc:mysql://localhost:3306/spring?serverTimezone=UTC&characterEncoding=utf-8

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值