SpringBoot--->05 Data 之 JDBC 整合

1、导入JDBC 模板对应jar包
 <!--jdbcTemplate -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
2、配置数据库链接信息(yml或者properties内编写)
3、编写配置类,并注入Bean,默认数据源为:Hikari
 package com.ZQQQ.config;

import org.junit.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;

/**druid 配置
 * JDBCTemplteConfig 配置
 */
@SpringBootTest
public class JDBCTemplteConfig {
    @Autowired
    DataSource dataSource;
    @Test
    void contextLoads(){
        System.out.println(dataSource.getClass());
        try {
            Connection connection = dataSource.getConnection();
            System.out.println(connection);
            connection.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

}
4、编写测试用例
package com.ZQQQ.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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * JDBCTemplte模板
 */
@RestController
public class JDBCController {
    @Autowired
    JdbcTemplate jdbcTemplate;

    /**
     * 查询user 表的全部信息
     *
     * List集合中的对象是一个Map对象,而这个Map对象的键是String类型,值是Object类型
     */
    @GetMapping("/UserList")
    public List<Map<String,Object>> UserList(){
        String sql="select * from user";
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
        return maps;
    }
    //自动提交事务
    @RequestMapping("/inserUser")
    public String insertUser(){
        String sql ="insert into user(name,age,email,create_time,modife_time,version)VALUES('五花肉',18,'78956670@qq.com','2021-08-12','2021-08-12',1)";
            jdbcTemplate.update(sql);
         return "successful";
    }
    @GetMapping("/updateUser")
    public String updateUser(){
        String sql ="update user set create_time='2021-08-01',modife_time ='2021-08-01' where id=9";
        jdbcTemplate.update(sql);
        return "successful";
    }
    @GetMapping("/deleteUesr")
    public String deleteUesr(){
        String sql ="delete from  user  where id =14";
        jdbcTemplate.update(sql);
        return "successful";
    }
}

总结:
如上省略了Mybatis 层,直接去操作数据库的,这样的方式不常用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值