0%

Spring Boot JDBC 连接数据库

springboot jdbc连接数据库的具体操作步骤以及在操作过程遇到的问题解决
参考来源:黑马程序员教程javaEE 《Spring Boot基础课件》

JDBC连接数据库

1. pom.xml配置maven依赖

<!-- MYSQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- Spring Boot JDBC -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

2. 进行属性文件的配置

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test
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=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5

3. 项目和包

4. java代码

4.1 SpringbootJdbcApplication.java

package com.seven;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringbootJdbcApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootJdbcApplication.class, args);
    }
}

4.2 OneController.java

package com.seven.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class OneController { 
    @Autowired
    private JdbcTemplate jdbcTemplate; 
    @RequestMapping("/")
    @ResponseBody
    public String index(){
        String sql = "insert into user (id,name) values (1,'zhangsan')";
        jdbcTemplate.execute(sql);
        System.out.println("执行完成");
        return "hello spring boot";
    }
}

5. 运行项目

运行SpringApplication.java中的main()方法

6. 进行访问

访问本地端口:[http://localhost:8080/](http://localhost:8080/]

7. 报错:java.sql.SQLNonTransientConnectionException

Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: The server time zone value '?????????' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.

8. 解决办法

在 application.properties 文件 url 后面添加 ?serverTimezone=UTC

spring.datasource.url=jdbc:mysql://localhost:3306/testapplication.

在此运行,访问,显示成功。

9. 未解决时可能出现的问题

- application.properties文件配置的url其中:Mysql6.0需要的驱动类名为:com.mysql.cj.jdbc.Driver,而Mysql5需要的驱动类名为:com.mysql.jdbc.Driver
- 数据库链接地址错误("/"的数量):spring.datasource.url=jdbc:mysql://127.0.0.1:3306/yourDB_name
- 数据库账号密码错误
- 数据库未启动或者无权访问,需要增加权限
-------------    本文结束  感谢您的阅读    -------------