【JavaWeb】JDBC实战

深藏阁楼爱情的钟 2024-04-26 03:26 179阅读 0赞

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

阅读指南

  • 一、需求
  • 二、准备环境
  • 三、查询所有数据
  • 四、添加数据
  • 五、修改数据
  • 六、删除数据

一、需求


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

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

二、准备环境


① 准备数据库表 tb_brand

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

在这里插入图片描述

② 在 pojo 包下创建实体类 Brand

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

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

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

③ 测试用例

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

在这里插入图片描述

三、查询所有数据


步骤:

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

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

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

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

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

在这里插入图片描述

查询所有数据功能完成!

四、添加数据


我们需要考虑的有 3 点:

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

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

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

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

在这里插入图片描述

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

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

五、修改数据


我们需要考虑的有 3 点:

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

    //修改数据
    @Test
    public void testUpdate() throws Exception {

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

    }

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

在这里插入图片描述

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

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

六、删除数据


我们需要考虑的有 3 点:

  1. 编写哪种 SQL 语句:delete
  2. SQL 语句是否需要参数? 只需要 id
  3. 返回的结果如何封装?boolean

    //删除数据
    @Test
    public void testDeleteById() throws Exception {

    1. // 模拟接收页面提交的参数
    2. int id = 4;
    3. //1. 获取Connection
    4. //加载配置文件
    5. Properties prop = new Properties();
    6. prop.load(new FileInputStream("D:\\IdeaProjects\\jdbc_demo\\src\\druid.properties"));
    7. //获取连接池对象
    8. DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
    9. //获取数据库连接 Connection
    10. Connection conn = dataSource.getConnection();
    11. //2. 定义SQL
    12. String sql = "delete from tb_brand where id = ?";
    13. //3. 获取pstmt对象
    14. PreparedStatement pstmt = conn.prepareStatement(sql);
    15. //4. 设置参数
    16. pstmt.setInt(1, id);
    17. //5. 执行SQL
    18. int count = pstmt.executeUpdate(); //影响的行数
    19. //6. 处理结果
    20. System.out.println(count > 0);
    21. //7. 释放资源
    22. pstmt.close();
    23. conn.close();

    }

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

在这里插入图片描述

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

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

发表评论

表情:
评论列表 (有 0 条评论,179人围观)

还没有评论,来说两句吧...

相关阅读

    相关 git实战(六):模拟实战

    之前我们是在本地环境搭建了一个git,然后操作了代码提交,回退等,现在我们需要在一台服务器进行操作,让我们的开发变得更加规范 一)服务器上创建文件夹 我们得有一台服务器,