当前位置: 首页 > article >正文

使用JdbcTemplate 进行数据库的增、删、改、查

一、概述

1、为什么选择 Spring Boot ?

Spring Boot 是目前 Java 社区最流行、最有影响力的技术之一,也是下一代企业级应用开发的首选技术。Spring Boot 由 Spring 衍生而来,继承了其所有的有点,为开发者带来了巨大的便利。

“We use a lot of the tools that come with the Spring framework and reap the benefits of having a lot of the out of the box solutions, and not having to worry about writing a ton of additional code—so that really saves us some time and energy.”

     -----SEAN GRAHAM, APPLICATION TRANSFORMATION LEAD, DICK’S SPORTING GOODS

“我们使用了Spring框架附带的许多工具,并获得了许多开箱即用的解决方案,而不必担心编写大量额外的代码,因此这确实节省了我们的时间和精力。”
                                                                      -----肖恩·格雷厄姆,迪克体育用品应用转型主管

2、Spring Boot 3特性:

  • Spring Boot 简化开发
  • 继承了 Spring 的优点
  • 可以快速创建独立运行的 Spring 项目
  • 习惯有配置(少量配置即可开发)
  • 拥有大量的自动配置

3、Spring Boot  对数据库连接支持

        Spring Boot 具有自动配置特性,能够根据应用程序的依赖和配置信息,自动配置数据源。 在大多数情况下,Spring Boot将自动配置为使用HikariCP作为默认数据库连接池。 开发者只需要提供必要的数据库连接信息,Spring Boot就能自动完成数据源的配置过程,极大地简化了开发者的工作。

Spring Boot 提供的与数据相关的场景启动器

二、使用JdbcTemplate 进行数据库的增、删、改、查

1、什么是JdbcTemplate

JdbcTemplated 是Spring 对 JDBC 的封装,使 JDBC 更加易于使用。更为关键的是,JdbcTemplate 对象也是通过自动配置机制注册到 IOC 容器中的。

JdbcTemplate官方文档

2、使用

1.引入依赖
<dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <scope>runtime</scope>
    </dependency>

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

<dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-jdbc</artifactId>
        <version>3.3.5</version>
</dependency>
2.配置数据库相关的数据
spring:
  datasource:
    name: big_event
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/big_event?useUnicode=true&serverTimezone=Asia/Shanghai&characterEncoding=utf-8&autoReconnect=true&useSSL=false&allowMultiQueries=true&useAffectedRows=true
    username: root   # 自己数据库的用户名
    password: 123456   # 数据库登录的密码
3.创建一个数据表
create table jdbc_test
(
    ds_id   int auto_increment comment '主键id'
        primary key,
    ds_type varchar(100) null comment '数据源类型',
    ds_name varchar(100) null comment '数据源名称'
)
    comment '数据源配置表' engine = InnoDB;

4.创建控制包 controller 下的 JdbcController.java
package com.example.demo.controller;

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

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

@RestController
public class JdbcController {
    @Autowired
    JdbcTemplate jdbcTemplate;

    @GetMapping("/insert")
    public String insert(String type, String name) {
        if (StringUtils.isEmpty(type) || StringUtils.isEmpty(name)) {
            return "参数错误";
        }
        try {
            jdbcTemplate.update("insert into jdbc_test(ds_type, ds_name) values(?, ?)", type, name);
            return "插入成功";
        } catch (Exception e) {
            return "插入失败: " + e.getMessage();
        }
    }

    @GetMapping("/delete")
    public String delete(int id) {
        if (id < 0) {
            return "参数错误";
        }
        try {
            int rowsAffected = jdbcTemplate.update("delete from jdbc_test where ds_id = ?", id);
            if (rowsAffected == 0) {
                return "未找到该条数据";
            }
            return "删除成功";
        } catch (Exception e) {
            return "删除失败: " + e.getMessage();
        }
    }

    @GetMapping("/update")
    public String update(int id, String type, String name) {
        if (id < 0 || StringUtils.isEmpty(type) || StringUtils.isEmpty(name)) {
            return "参数错误";
        }
        try {
            int rowsAffected = jdbcTemplate.update("update jdbc_test set ds_name = ?, ds_type = ? where ds_id = ?", name, type, id);
            if (rowsAffected == 0) {
                return "未找到该条数据";
            }
            return "更新成功";
        } catch (Exception e) {
            return "更新失败: " + e.getMessage();
        }
    }

    @GetMapping("/selects")
    public List<Map<String, Object>> selects() {
        try {
            List<Map<String, Object>> result = jdbcTemplate.queryForList("select * from jdbc_test");
            return result;
        } catch (Exception e) {
            throw new RuntimeException("查询失败: " + e.getMessage(), e);
        }
    }
}

3、验证

1.insert 验证:在浏览器中输入
http://localhost:8080/insert?type=test&name=测试类

结果如下:  

表中显示: 

 2.update 验证:在浏览器中输入
http://localhost:8080/update?id=3&type=test1&name=测试类~~~~~~~~

结果如下: 

表中显示: 

3.delete验证:在浏览器中输入
http://localhost:8080/delete?id=3

 结果如下: 

 表中显示: 

4.selects验证:在浏览器中输入
http://localhost:8080/selects

结果如下: 


http://www.kler.cn/a/381263.html

相关文章:

  • ServletContext 对象介绍
  • Redis持久化机制——针对实习面试
  • 力扣11.4
  • 微信小程序 基于协同过滤算法的的校园音乐推荐系统
  • 大客户营销数字销售实战讲师培训讲师唐兴通专家人工智能大模型销售客户开发AI大数据挑战式销售顾问式销售专业销售向高层销售业绩增长创新
  • 低代码解锁跨平台应用开发新境界
  • Elasticsearch核心概念
  • [渲染层网络层错误] net::ERR_CONTENT_LENGTH_MISMATCH 问题解决
  • 【TextIn:开源免费的AI智能文字识别产品(通用文档智能解析识别、OCR识别、文档格式转换、篡改检测、证件识别等)】
  • 利用爬虫爬取网站信息
  • spring-data-aop Repository层的增删查改
  • 基于C#的Windows编程:后台窗口和坐标转换
  • 网络原理(应用层)->HTTPS解
  • odrive代码阅读笔记
  • 图说复变函数论重大错误:将无穷多各异平面误为同一面
  • Python常用脚本集锦
  • Linux下复制粘贴快捷键
  • neo4j浅析
  • [Linux] 进程控制之创建和终止
  • 【SQL50】day 1