likes
comments
collection
share

【JavaWeb】JDBC实战

作者站长头像
站长
· 阅读数 9

需求

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

  • 添加:添加品牌
  • 删除:根据 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;

【JavaWeb】JDBC实战

② 在 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 +
                '}';
    }
}

③ 测试用例

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

【JavaWeb】JDBC实战

查询所有数据

步骤:

  1. 获取 Connection
  2. 定义 SQLselect * from tb_brand;
  3. 获取 PreparedStatement 对象
  4. 设置参数:不需要
  5. 执行 SQL
  6. 处理结果:List<Brand>
  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();
    }
}

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

【JavaWeb】JDBC实战

查询所有数据功能完成!

添加数据

我们需要考虑的有 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();
}

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

【JavaWeb】JDBC实战

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

【JavaWeb】JDBC实战

添加数据功能完成!

修改数据

我们需要考虑的有 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();
}

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

【JavaWeb】JDBC实战

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

【JavaWeb】JDBC实战

修改数据功能完成!

删除数据

我们需要考虑的有 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();
}

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

【JavaWeb】JDBC实战

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

【JavaWeb】JDBC实战