springboot整合JDBC

JDBCcontroller

package com.jdbcstudy.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 {

    @Autowired
    JdbcTemplate jdbcTemplate;

    //查询数据库的所有信息
    @GetMapping("/userlist")
    public List<Map<String,Object>> studentList(){
        String sql = "select * from student";
        List<Map<String,Object>> list_maps = jdbcTemplate.queryForList(sql);
        return list_maps;
    }

    //新增数据
    @GetMapping("/adduser")
    public String addUser(){
        String sql ="insert into studentsql.student(id,name,age) values (6,'xiaoming','55')";
        jdbcTemplate.update(sql);
        return "add ok";

    }

    //修改
    @GetMapping("/updateUser/{id}")
    public String updateUser(@PathVariable("id") int id){
        String sql ="update studentsql.student set name=?,age=? where id="+id;
        //封装
        Object[] objects = new Object[2];
        objects[0] = "小明";
        objects[1] = "188";
        jdbcTemplate.update(sql,objects);
        return "updata ok";

    }
    //删除
    @GetMapping("/deleteUser/{id}")
    public String deleteUser(@PathVariable("id") int id){
        String sql ="delete from studentsql.student where id = ?";
        jdbcTemplate.update(sql,id);
        return "delete ok";

    }
}

application.yml

spring:
  datasource:
    username: root
    password: 123
    url: jdbc:mysql://localhost:3306/studentsql?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver

数据库测试

package com.jdbcstudy;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

@SpringBootTest
class SpringbootJdbcDataApplicationTests {

    @Autowired
    DataSource dataSource;
    @Test
    void contextLoads() throws SQLException {
        //查看一下默认的数据源:class com.zaxxer.hikari.HikariDataSource
        System.out.println(dataSource.getClass());

        //获得数据库连接
        Connection connection = dataSource.getConnection();
        System.out.println(connection);

        //xxxx Template:springboot已经配置好的模板bean,拿来即用

        //数据库关闭
        connection.close();

    }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值