【JavaWeb学习记录08】JDBC(2)

3.4 数据库连接池

3.4.1 简介
  • 数据库连接池是一个容器,负责分配、管理数据库连接(Connection)
  • 允许应用程序重复使用一个现有的数据库连接,而不是重新建立一个
  • 释放空闲空间超过最大空闲时间的数据库连接来避免因为没有释放数据库连接而引起的数据库连接遗漏
  • 好处
    • 资源重用
    • 提升系统响应速度
    • 避免数据库连接遗漏

创建Connection对象并将其销毁的过程特别耗费计算机性能和时间

数据库使用数据库连接池,达到Connection对象的重复使用

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-oTR6V29R-1663687624281)(C:\Users\18517\AppData\Roaming\Typora\typora-user-images\image-20220828071831275.png)]

连接池是在一开始就创建好了一些连接(Connection)对象存储起来。用户需要连接数据库时,不需要自己创建连接,而只需要从连接池中获取一个连接进行使用,使用完毕后再将连接对象归还给连接池;这样就可以起到资源重用,也节省了频繁创建连接销毁连接所花费的时间,从而提升了系统响应的速度

3.4.2 数据连接池的实现
1. 标准接口:DataSource

提供了获取连接的功能

Connection getConnection()

不需要通过 DriverManager 对象获取 Connection 对象,而是通过连接池 DataSource 获取 Connection 对象

2. 常见数据库连接池
  • DBCP
  • C3P0
  • Druid
3. Druid
  • Druid 连接池,alibaba开源的数据库连接池项目
  • 功能强大,性能优秀,Java语言最好的数据库连接池之一
3.4.3 Druid 使用
  • 导入jar包 druid-1.1.12.jar
  • 定义配置文件
  • 加载配置文件
  • 获取数据库连接池对象
  • 获取连接

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5fGHkyuE-1663687624288)(C:\Users\18517\AppData\Roaming\Typora\typora-user-images\image-20220828081210115.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IULnzzB5-1663687624289)(C:\Users\18517\AppData\Roaming\Typora\typora-user-images\image-20220828081157145.png)]

druid.properties 配置文件如下:

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///itcast?useSSL=false&useServerPrepStmts=true
username=root
password=chenmo
# 初始化连接数量
initialSize=5
# 最大连接数
maxActive=10
# 最大等待时间
maxWait=3000

使用druid的代码如下:

package druid;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.util.Properties;

/**
 * @Author 晨默
 * @Date 2022/8/28 7:57
 */
public class DruidDemo {
    public static void main(String[] args) throws Exception {
        // 1. 导入jar包
        // 2. 定义配置文件
        // 3. 加载配置文件
        Properties prop = new Properties();
        prop.load(new FileInputStream("src/druid.properties"));
        // 4. 获取连接池对象
        DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);

        // 5. 获取数据库连接 Connection
        Connection connection = dataSource.getConnection();
        System.out.println(connection); // 获取到了连接后就可以继续做其他操作了
        System.out.println(System.getProperty("user.dir"));
    }
}

结果如下:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-R9zvAYOK-1663687624291)(C:\Users\18517\AppData\Roaming\Typora\typora-user-images\image-20220828081404294.png)]

3.5 JDBC案例

1. 数据库表 tb_rand

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-aNAewiBo-1663687624291)(C:\Users\18517\AppData\Roaming\Typora\typora-user-images\image-20220828095444276.png)]

2. 实体类 Brand
package pojo;

import java.io.InputStream;

/**
 * @Author 晨默
 * @Date 2022/8/28 8:27
 */
public class Brand {
    // id 主键
    private Integer id;
    // 品牌名称
    private String brandName;
    // 企业名称
    private String companyName;
    // 排序字段
    private Integer ordered;
    // 描述信息
    private String description;
    // 状态:0:禁用  1:启用
    private Integer status;

    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 +
                '}';
    }
}
3. 查询所有信息
package pojo;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * @Author 晨默
 * @Date 2022/8/28 8:30
 */

/**
 * 查询所有数据
 * 1. SQL:select * from tb_brand
 * 2. 参数:不需要
 * 3. 结果:List<Brand>
 */
public class testSelectAll {
    public static void main(String[] args) throws Exception {
        // 1. 获取Connection
        // 3. 加载配置文件
        Properties prop = new Properties();
        prop.load(new FileInputStream("src/druid.properties"));
        // 4. 获取连接池对象
        DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);

        // 5. 获取数据库连接 Connection
        Connection conn = dataSource.getConnection();
        // 2. 定义SQL
        String sql = "select * from tb_rand";
        // 3. 获取pstmt对象
        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();
    }
}
// 打印结果为:
[Brand{id=1, brandName='三只松鼠', companyName='三只松鼠股份有限公司', ordered=5, description='好吃不上火', status=0}, Brand{id=2, brandName='华为', companyName='华为技术有限公司', ordered=100, description='华为致力于把数字世界带入每个人、每个家庭、每个组织,构建万物互联的智能世界', status=1}, Brand{id=3, brandName='小米', companyName='小米科技有限公司', ordered=50, description='are you OK', status=1}]

4. 添加数据
package pojo;

/**
 * @Author 晨默
 * @Date 2022/8/28 9:03
 */

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Properties;

/**
 * 添加数据
 * 1. SQL:insert into tb_brand(brand_name, company_name, ordered, description, status) values(?,?,?,?,?);
 * 2. 参数:需要,除了id之外的所有参数信息
 * 3. 结果:boolean
 * */
public class testAdd {
    public static void main(String[] args) throws Exception {
        Properties prop = new Properties();
        prop.load(new FileInputStream("src/druid.properties"));

        DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
        Connection connection = dataSource.getConnection();

        // 接收页面提交的参数
        String brandName = "香飘飘";
        String companyName = "香飘飘";
        int ordered = 1;
        String description = "绕地球一圈";
        int status = 1;
        String sql = "insert into tb_rand(brand_name, company_name, ordered, description, status) values(?,?,?,?,?);";

        PreparedStatement pstmt = connection.prepareStatement(sql);
        pstmt.setString(1,brandName);
        pstmt.setString(2,companyName);
        pstmt.setInt(3,ordered);
        pstmt.setString(4,description);
        pstmt.setInt(5,status);

        int count = pstmt.executeUpdate();
        System.out.println(count > 0); // true

        pstmt.close();
        connection.close();
    }
}
5. 修改数据
package pojo;

/**
 * @Author 晨默
 * @Date 2022/8/28 9:37
 */

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Properties;

/**
 * 修改数据
 * 1. SQL:
 *      update tb_rand
 *          set brand_name = ?,
 *          company_name = ?,
 *          ordered = ?,
 *          description = ?,
 *          status = ?
 *      where id = ?;
 * 2. 参数:需要,所有参数信息
 * 3. 结果:boolean
 * */
public class testUpdate {
    public static void main(String[] args) throws Exception {
        Properties prop = new Properties();
        prop.load(new FileInputStream("src/druid.properties"));

        DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
        Connection connection = dataSource.getConnection();

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

        String sql = """
                update tb_rand
                     set brand_name = ?,
                     company_name = ?,
                     ordered = ?,
                     description = ?,
                     status = ?
                where id = ?;""";

        PreparedStatement pstmt = connection.prepareStatement(sql);
        pstmt.setString(1,brandName);
        pstmt.setString(2,companyName);
        pstmt.setInt(3,ordered);
        pstmt.setString(4,description);
        pstmt.setInt(5,status);
        pstmt.setInt(6,id);

        int count = pstmt.executeUpdate();
        System.out.println(count > 0); // true

        pstmt.close();
        connection.close();
    }
}
6. 删除数据
package pojo;

/**
 * @Author 晨默
 * @Date 2022/8/28 9:48
 */

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 1. SQL:delete from tb_rand where id = ?;
 * 2. 参数: 需要,id
 * 3. 结果: boolean
 * */
public class testDeleteById {
    public static void main(String[] args) throws Exception {
        int id = 4;

        Properties prop = new Properties();
        prop.load(new FileInputStream("src/druid.properties"));

        DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
        Connection connection = dataSource.getConnection();

        String sql = "delete from tb_rand where id = ?;";

        PreparedStatement pstmt = connection.prepareStatement(sql);
        pstmt.setInt(1,id);

        int count = pstmt.executeUpdate();
        System.out.println(count > 0); // true

        pstmt.close();
        connection.close();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mathison晨默

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值