• 【JavaWeb】JDBC实战


    🔥 本文由 程序喵正在路上 原创,CSDN首发!
    💖 系列专栏:👉JavaWeb从入门到实战
    🌠 首发时间:2022年9月3日
    🦋 欢迎关注🖱点赞👍收藏🌟留言🐾
    🌟 一以贯之的努力 不得懈怠的人生

    一、需求


    完成商品品牌数据的增删改查操作,具体如下

    • 添加:添加品牌
    • 删除:根据 id 删除
    • 修改:根据 id 修改
    • 查询:查询所有数据

    二、准备环境


    ① 准备数据库表 tb_brand

    -- 删除tb_brand表
    drop table if exists tb_brand;
    
    -- 创建tb_brand表
    create table tb_brand (
        -- id 主键
        id int primary key auto_increment,
        -- 品牌名称
        brand_name varchar(20),
        -- 企业名称
        company_name varchar(20),
        -- 排序字段
        ordered int,
        -- 描述信息
        description varchar(100),
        -- 状态:0:禁用  1:启用
        status int
    );
    -- 添加数据
    insert into tb_brand (brand_name, company_name, ordered, description, status)
    values ('三只松鼠', '三只松鼠股份有限公司', 5, '好吃不上火', 0),
           ('华为', '华为技术有限公司', 100, '华为致力于把数字世界带入每个人、每个家庭、每个组织,构建万物互联的智能世界', 1),
           ('小米', '小米科技有限公司', 50, 'are you ok', 1);
    
    SELECT * FROM tb_brand;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    在这里插入图片描述

    ② 在 pojo 包下创建实体类 Brand

    在品牌类里面我们首先肯定要做的是定义相关的变量,也就是前一步创建表的那些变量;然后生成相关 getset 方法,还有 toString 方法,建议使用 IDEA 快捷键 Alt + Insert,再按住 Ctrl 键选中所有来生成

    在实体类中,基本数据类型建议使用其对应的包装类型

    /*
        品牌
     */
    public class Brand {
        // id 主键
        private Integer id;
        // 品牌名称
        private String brandName;
        // 企业名称
        private String companyName;
        // 排序字段
        private Integer ordered;
        // 描述信息
        private String description;
        // 状态:0:禁用  1:启用
        //在这种情况下,建议不要用基本数据类型int,因为有默认值0
        private Integer status;
    
        //get和set方法
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getBrandName() {
            return brandName;
        }
    
        public void setBrandName(String brandName) {
            this.brandName = brandName;
        }
    
        public String getCompanyName() {
            return companyName;
        }
    
        public void setCompanyName(String companyName) {
            this.companyName = companyName;
        }
    
        public Integer getOrdered() {
            return ordered;
        }
    
        public void setOrdered(Integer ordered) {
            this.ordered = ordered;
        }
    
        public String getDescription() {
            return description;
        }
    
        public void setDescription(String description) {
            this.description = description;
        }
    
        public Integer getStatus() {
            return status;
        }
    
        public void setStatus(Integer status) {
            this.status = status;
        }
    
        @Override
        public String toString() {
            return "Brand{" +
                    "id=" + id +
                    ", brandName='" + brandName + '\'' +
                    ", companyName='" + companyName + '\'' +
                    ", ordered=" + ordered +
                    ", description='" + description + '\'' +
                    ", status=" + status +
                    '}';
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79

    ③ 测试用例

    src 下新建一个 example 包来放置测试的文件,创建一个 BrandTest 类方便我们后面写测试增删改查的操作

    在这里插入图片描述

    三、查询所有数据


    步骤:

    1. 获取 Connection
    2. 定义 SQLselect * from tb_brand;
    3. 获取 PreparedStatement 对象
    4. 设置参数:不需要
    5. 执行 SQL
    6. 处理结果:List
    7. 释放资源

    其中 1、3、5、7 四个步骤是不变的

    BrandTest 类中按照上列步骤写一个测试方法 testSelectAll()

    import com.alibaba.druid.pool.DruidDataSourceFactory;
    import org.junit.Test;
    import pojo.Brand;
    
    import javax.sql.DataSource;
    import java.io.FileInputStream;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.util.*;
    
    public class BrandTest {
    
        @Test
        public void testSelectAll() throws Exception {
            //1. 获取Connection
            //加载配置文件
            Properties prop = new Properties();
            prop.load(new FileInputStream("D:\\IdeaProjects\\jdbc_demo\\src\\druid.properties"));
    
            //获取连接池对象
            DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
    
            //获取数据库连接 Connection
            Connection conn = dataSource.getConnection();
    
            //2. 定义SQL
            String sql = "select * from tb_brand";
    
            //3. 获取pstmt对象
            PreparedStatement pstmt = conn.prepareStatement(sql);
    
            //4. 设置参数
    
            //5. 执行SQL
            ResultSet rs = pstmt.executeQuery();
    
            //6. 处理结果
            Brand brand = null;
            List<Brand> brands = new ArrayList<>();
    
            while(rs.next()){
                //获取数据
                int id = rs.getInt("id");
                String brandName = rs.getString("brand_name");
                String companyName = rs.getString("company_name");
                int ordered = rs.getInt("ordered");
                String description = rs.getString("description");
                int status = rs.getInt("status");
                //封装Brand对象
                brand = new Brand();
                brand.setId(id);
                brand.setBrandName(brandName);
                brand.setCompanyName(companyName);
                brand.setOrdered(ordered);
                brand.setDescription(description);
                brand.setStatus(status);
                //装载集合
                brands.add(brand);
            }
            //打印一下
            for(Brand b:brands){
                System.out.println(b);
            }
    
            //7. 释放资源
            rs.close();
            pstmt.close();
            conn.close();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71

    然后,鼠标双击方法名,右击运行这个方法试试看,结果如下:

    在这里插入图片描述

    查询所有数据功能完成!

    四、添加数据


    我们需要考虑的有 3 点:

    1. 编写哪种 SQL 语句:insert
    2. SQL 语句是否需要参数? 需要,除了 id 外的所有数据
    3. 返回的结果如何封装?boolean

    注意:添加数据这一步我们是不需要从用户那里获取 id 的,因为数据库会自动生成

    //添加数据
    @Test
    public void testAdd() throws Exception {
        // 模拟接收页面提交的参数
        String brandName = "香飘飘";
        String companyName = "香飘飘";
        int ordered = 1;
        String description = "绕地球一圈";
        int status = 1;
    
    
        //1. 获取Connection
        //加载配置文件
        Properties prop = new Properties();
        prop.load(new FileInputStream("D:\\IdeaProjects\\jdbc_demo\\src\\druid.properties"));
    
        //获取连接池对象
        DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
    
        //获取数据库连接 Connection
        Connection conn = dataSource.getConnection();
    
        //2. 定义SQL
        String sql = "insert into tb_brand(brand_name, company_name, ordered, description, status) values(?,?,?,?,?);";
    
        //3. 获取pstmt对象
        PreparedStatement pstmt = conn.prepareStatement(sql);
    
        //4. 设置参数
        pstmt.setString(1, brandName);
        pstmt.setString(2, companyName);
        pstmt.setInt(3, ordered);
        pstmt.setString(4, description);
        pstmt.setInt(5, status);
    
        //5. 执行SQL
        int count = pstmt.executeUpdate();  //影响的行数
    
        //6. 处理结果
        System.out.println(count > 0);
    
        //7. 释放资源
        pstmt.close();
        conn.close();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45

    运行结果为 true,表明添加成功:

    在这里插入图片描述

    查看了一下表格,发现数据已经添加成功:

    在这里插入图片描述
    添加数据功能完成!

    五、修改数据


    我们需要考虑的有 3 点:

    1. 编写哪种 SQL 语句:update
    2. SQL 语句是否需要参数? 需要所有数据
    3. 返回的结果如何封装?boolean
    //修改数据
    @Test
    public void testUpdate() throws Exception {
        // 模拟接收页面提交的参数
        String brandName = "香飘飘";
        String companyName = "香飘飘";
        int ordered = 1000;
        String description = "绕地球十圈";
        int status = 1;
        int id = 4;
    
        //1. 获取Connection
        //加载配置文件
        Properties prop = new Properties();
        prop.load(new FileInputStream("D:\\IdeaProjects\\jdbc_demo\\src\\druid.properties"));
        //获取连接池对象
        DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
        //获取数据库连接 Connection
        Connection conn = dataSource.getConnection();
    
        //2. 定义SQL
        String sql = " update tb_brand\n" +
                "         set brand_name  = ?,\n" +
                "         company_name= ?,\n" +
                "         ordered     = ?,\n" +
                "         description = ?,\n" +
                "         status      = ?\n" +
                "     where id = ?";
    
        //3. 获取pstmt对象
        PreparedStatement pstmt = conn.prepareStatement(sql);
    
        //4. 设置参数
        pstmt.setString(1, brandName);
        pstmt.setString(2, companyName);
        pstmt.setInt(3, ordered);
        pstmt.setString(4, description);
        pstmt.setInt(5, status);
        pstmt.setInt(6, id);
    
        //5. 执行SQL
        int count = pstmt.executeUpdate();  //影响的行数
    
        //6. 处理结果
        System.out.println(count > 0);
    
        //7. 释放资源
        pstmt.close();
        conn.close();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50

    运行结果为 true,表明修改成功:

    在这里插入图片描述

    查看了一下表格,发现数据已经修改成功:

    在这里插入图片描述
    修改数据功能完成!

    六、删除数据


    我们需要考虑的有 3 点:

    1. 编写哪种 SQL 语句:delete
    2. SQL 语句是否需要参数? 只需要 id
    3. 返回的结果如何封装?boolean
    //删除数据
    @Test
    public void testDeleteById() throws Exception {
        // 模拟接收页面提交的参数
        int id = 4;
    
        //1. 获取Connection
        //加载配置文件
        Properties prop = new Properties();
        prop.load(new FileInputStream("D:\\IdeaProjects\\jdbc_demo\\src\\druid.properties"));
        //获取连接池对象
        DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
        //获取数据库连接 Connection
        Connection conn = dataSource.getConnection();
    
        //2. 定义SQL
        String sql = "delete from tb_brand where id = ?";
    
        //3. 获取pstmt对象
        PreparedStatement pstmt = conn.prepareStatement(sql);
    
        //4. 设置参数
        pstmt.setInt(1, id);
    
        //5. 执行SQL
        int count = pstmt.executeUpdate();  //影响的行数
    
        //6. 处理结果
        System.out.println(count > 0);
    
        //7. 释放资源
        pstmt.close();
        conn.close();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    运行结果为 true,表明删除成功:

    在这里插入图片描述

    查看了一下表格,发现数据已经删除:

    在这里插入图片描述
    删除数据功能完成!

  • 相关阅读:
    ubuntu 20.04如何切换gcc/g++/python的版本
    11月26日:操作系统实验杂记 msgget(创建消息队列) msgsnd(发送消息) msggrcv(接收消息) msgctl(控制消息队列)
    DAY59 503.下一个更大元素II + 42. 接雨水
    SpringBoot之整合WebSocket服务并兼容IE8浏览器的方式
    21. 概率与统计 - 数学期望、统计描述&分布
    nodejs+vue旅游推荐系统-计算机毕业设计
    六、函数和变量的命名
    十三、Linux文件目录指令
    【代码精读】optee中如何添加一个外设
    第68步 时间序列建模实战:ARIMA建模(Matlab)
  • 原文地址:https://blog.csdn.net/weixin_62511863/article/details/126661641