栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot向数据库插入数据

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot向数据库插入数据

springboot向数据库插入数据 pom.xml

记住把mysql依赖的版本改成6.0.6



    4.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
            
        
    



application.properties
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里边的内容写错了。总之终于解决了,看到数据库里边有数据就很开心!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/959646.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号