记住把mysql依赖的版本改成6.0.6
application.properties4.0.0 org.springframework.boot spring-boot-starter-parent 2.7.0 com JDBC 0.0.1-SNAPSHOT JDBC JDBC 1.8 org.springframework.boot spring-boot-starter-jdbc org.springframework.boot spring-boot-starter-jdbc org.springframework.boot spring-boot-starter-web mysql mysql-connector-java 6.0.6 org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-maven-plugin
spring.datasource.driver=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/springvue?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false spring.datasource.username=root spring.datasource.password=lz666.UserService.java
package com.jdbc.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private JdbcTemplate jdbcTemplate;
public void add(){
jdbcTemplate.execute("insert into user1 values('1','2')");
}
}
UserController.java
package com.jdbc.Controller;
import com.jdbc.Service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@Controller
public class UserController {
@Autowired
private UserService userservice;
@RequestMapping("/user")
@ResponseBody
public void test(){
userservice.add();
}
}
总结最后记得访问 http://localhost:8080/user ,如果出来是空白页的话就成功啦!
最开始连接数据库的时候报了很多错,一个是没有加@ResponseBody,还有一个是properties里边的内容写错了。总之终于解决了,看到数据库里边有数据就很开心!



