JDBC数据库连接池&Druid的使用&JDBC练习

目录

一、数据库连接池简介

二、数据库连接池的实现

三、练习完成商品品牌数据的增删改查操作

3.1 查询所有数据

3.2 添加数据

3.3 修改数据(根据id)

3.4 删除数据(根据id)


一、数据库连接池简介

  • 数据库连接池是个容器,负责分配、管理连接数据库连接(Connection)。
  • 它允许应用程序重复使用一个现有的数据库连接,而不是都在重新建立一个。
  • 释放空间时间超过最大空闲时间的数据库连接来避免因为没有释放数据库连接而引起的数据库连接遗漏

好处:

  • 资源重用
  •  提升系统响应速度
  •  避免数据库连接遗漏

 二、数据库连接池的实现

标准接口:DataSource

        官方(SUN)提供的数据库连接池标准接口,由第三方组织实现此接口。

        功能:获取连接

        Connection getConnection()

 常见的数据库连接池:

  • DBCP
  • C3P0
  • Druid

Druid(德鲁伊):

  • Druid连接池是阿里巴巴开源的数据库连接池项目。
  • 功能强大,性能优秀,是java语言最好的数据库连接池之一。 

Druid使用步骤:

  1. 导入jar包druid-1.1.12jar
  2. 定义配置文件
  3. 加载配置文件
  4. 获取数据库连接池对象
  5. 获取连接

三、练习完成商品品牌数据的增删改查操作

  • 查询:查询所有数据

  • 添加:添加品牌

  • 修改:根据id修改

  • 删除:根据id删除 

环境准备:

  • 数据库表tb_brand
  • 实体类Brand
  • 测试用例 

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;

idea快捷键: 

  •  * alt+鼠标左键,整列编辑
  •  * ctrl+r替换
  •  * ctrl+alt+L格式化
  • *alt+insert构造方法

实体类:

/**
 * 品牌
 * alt+鼠标左键,整列编辑
 * ctrl+r替换
 * ctrl+alt+L格式化
 * alt+insert构造方法
 * 在实体类中基本数据类型建议使用其对应的包装类型
 */
public class Brand {
    //id 主键
    private Integer id;
    //品牌名称
    private String brandName;
    //企业名称
    private String companyName;
    //排序字段
    private Integer ordered;
    //描述信息
    private String description;
    //状态:0:禁用  1:启用
    private Integer status;//int有默认值0,0有业务含义:禁用。所以我们不用基本数据类型,而常用包装类型Integer,对象的默认值为null
}

   3.1 查询所有数据

  1. 获取Connection
  2. 定义SQL:select * from tb_brand;
  3. 获取PrepareStatement对象
  4. 设置参数:不需要
  5. 执行SQL
  6. 处理结果:List<Brand>
  7. 释放资源 
/**
     * 查询所有
     * 1.SQl:select *  from tb_brand
     * 2.参数:不需要
     * 3.返回结果:List<Brand>
     */
    @Test
    public  void testSelectAll() throws Exception {
        //1.获取Connection对象
        //加载配置文件
        Properties prop = new Properties();
        prop.load(new FileInputStream("src/druid.properties"));//加载配置文件

        //获取连接池对象
        DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);

        //获取数据库连接Connection
        Connection conn = dataSource.getConnection();
      //  System.out.println(System.getProperty("user.dir"));//查看当前路径

        //2.d定义SQL语句
        String sql = "select * from tb_brand";

        //3.获取PreparedStatement对象
        PreparedStatement pstmt = conn.prepareStatement(sql);

        //4.设置参数

        //5.执行sql
        ResultSet rs = pstmt.executeQuery();

        //6.处理结果List <Brand>封装Brand对象,装载List集合

        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);

        }
        System.out.println(brands);

        //7.释放资源
        rs.close();
        pstmt.close();
        conn.close();

    }

3.2 添加数据

  1. 获取Connection
  2. 定义SQL:insert into tb_brand(brand_name,company_name,ordered,description,status)values(?,?,?,?,?);
  3. 获取PrepareStatement对象
  4. 设置参数:需要,除了id之外的所有数据
  5. 执行SQL
  6. 处理结果:返回boolean
  7. 释放资源 
 /**
     *添加数据
     * 1.SQl:insert into tb_brand(brand_name,company_name,ordered,description,status)values(?,?,?,?,?)
     * 2.参数:需要,除了id之外的所有参数信息
     * 3.返回结果:boolean
     */
    @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("src/druid.properties"));//加载配置文件

        //获取连接池对象
        DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);

        //获取数据库连接Connection
        Connection conn = dataSource.getConnection();
        //  System.out.println(System.getProperty("user.dir"));//查看当前路径

        //2.d定义SQL语句
        String sql = "insert into tb_brand(brand_name,company_name,ordered,description,status) values(?,?,?,?,?)";

        //3.获取PreparedStatement对象
        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.处理结果List <Brand>封装Brand对象,装载List集合
        System.out.println(count > 0);
        
        //7.释放资源

        pstmt.close();
        conn.close();

    }

3.3 修改数据(根据id)

  1. 获取Connection
  2. 定义SQL:update tb_brand
                      set brand_name = ?,
                            company_name = ?,
                            ordered = ?,
                            description = ?,
                            status = ?
                            where id = ?;
  3. 获取PrepareStatement对象
  4. 设置参数:需要,Brand对象所有数据
  5. 执行SQL
  6. 处理结果:返回boolean
  7. 释放资源 
/**
     *修改数据
     * 1.SQl:update tb_brand
             set brand_name = ?,
             company_name = ?,
             ordered = ?,
             description = ?,
             status = ?
             where id = ?
     * 2.参数:需要,除了id之外的所有参数信息
     * 3.返回结果:boolean
     */
    @Test
    public  void testUpdate() throws Exception {

        //接受页面提交的参数
        String brandName = "香飘飘";
        String companyName = "香飘飘";
        int ordered = 1000;
        String description = "绕地球3圈";
        int status = 1;
        int id = 4;

        //1.获取Connection对象
        //加载配置文件
        Properties prop = new Properties();
        prop.load(new FileInputStream("src/druid.properties"));//加载配置文件

        //获取连接池对象
        DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);

        //获取数据库连接Connection
        Connection conn = dataSource.getConnection();
        //  System.out.println(System.getProperty("user.dir"));//查看当前路径

        //2.d定义SQL语句
        String sql = "update tb_brand\n" +
                "             set brand_name = ?,\n" +
                "             company_name = ?,\n" +
                "             ordered = ?,\n" +
                "             description = ?,\n" +
                "             status = ?\n" +
                "        where id = ?";

        //3.获取PreparedStatement对象
        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.处理结果List <Brand>封装Brand对象,装载List集合
        System.out.println(count > 0);

        //7.释放资源

        pstmt.close();
        conn.close();

    }

3.4 删除数据(根据id)

  1. 获取Connection
  2. 定义SQL:delete from tb_brand where id = ?
  3. 获取PrepareStatement对象
  4. 设置参数:需要,id
  5. 执行SQL
  6. 处理结果:返回boolean
  7. 释放资源 
    /**
     *删除数据
     * 1.SQl:delete from tb_brand where id = ?
     * 2.参数:需要,id
     * 3.返回结果:boolean
     */
    @Test
    public  void testDeleteById() throws Exception {

        //接受页面提交的参数
        int id = 4;

        //1.获取Connection对象
        //加载配置文件
        Properties prop = new Properties();
        prop.load(new FileInputStream("src/druid.properties"));//加载配置文件

        //获取连接池对象
        DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);

        //获取数据库连接Connection
        Connection conn = dataSource.getConnection();
        //  System.out.println(System.getProperty("user.dir"));//查看当前路径

        //2.d定义SQL语句
        String sql = "delete from tb_brand where id = ?";

        //3.获取PreparedStatement对象
        PreparedStatement pstmt = conn.prepareStatement(sql);

        //4.设置参数
        pstmt.setInt(1,id);
        //5.执行sql
        int count = pstmt.executeUpdate();//影响的行数

        //6.处理结果List <Brand>封装Brand对象,装载List集合
        System.out.println(count > 0);

        //7.释放资源

        pstmt.close();
        conn.close();

    }

猜你喜欢

转载自blog.csdn.net/weixin_48373085/article/details/128670538