其他分享
首页 > 其他分享> > Springboot整合JDBC

Springboot整合JDBC

作者:互联网

编写配置文件(application.yml)

spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/mybatis?useUnicode&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver

测试连接

@SpringBootTest
class Springboot04DataApplicationTests {
    @Autowired
    DataSource dataSource;
    @Test
    void contextLoads() throws SQLException {
        //查看一下默认的数据源
        System.out.println(dataSource.getClass());
        //获得数据库连接
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        System.out.println(connection);
        //关闭
        connection.close();
    }

}

 

查询数据库的数据

 

 

增删改查

package com.maple.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
public class JDBCController {
    //自动配置JdbcTemplate
    @Autowired
    JdbcTemplate jdbcTemplate;

    //查询数据库的所有信息
    //没有实体类,数据库中的东西,怎么获取?Map
    @GetMapping("/userList")
    public List<Map<String, Object>> userList(){
        String sql = "select * from user";
        List<Map<String, Object>> list_maps = jdbcTemplate.queryForList(sql);
        return list_maps;
    }
    //添加一个信息
    @GetMapping("/addUser")
    public String addUser(){
        String sql = "insert into mybatis.user(id,name,pwd) values(4,'烟雨如花','123456')";
        jdbcTemplate.update(sql);
        return "updata-ok";
    }
    //添加一个信息
    @GetMapping("/updateUse/{id}")
    public String updateUser(@PathVariable int id){
        String sql = "update mybatis.user set name = ?,pwd = ? where id = "+id;
        //封装
        Object[] objects = new Object[2];
        objects[0] = "赤色夫人";
        objects[1] = "123456";
        jdbcTemplate.update(sql,objects);
        return "updateUse-ok";
    }
    //添加一个信息
    @GetMapping("/delectUser/{id}")
    public String delectUser(@PathVariable int id){
        String sql = "delete from mybatis.user where id=?";
        jdbcTemplate.update(sql,id);
        return "delectUser-ok";
    }
}

 

标签:JDBC,String,springframework,jdbcTemplate,整合,sql,import,id,Springboot
来源: https://www.cnblogs.com/Mapleyang/p/16578228.html