JDBC——DBCP 数据库连接池的实现方式

本博客用于自己记录学习整理知识
首先需要导入jar包
commons-dbcp-1.4.jar、commons-pool-1.5.5.jar
在src文件下创建 dbcpconfig.properties 文件用于读取数据库

// dbcpconfig.properties 文件代码

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbcstudy?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&uesSSL=false
username=root
password=root

java工具类实现(简化连接数据库的过程)

private static DataSource dataSource=null;
    static {
        try{
            InputStream resourceAsStream = JdbcUtils_dbcp.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
            Properties properties = new Properties();
            properties.load(resourceAsStream);

            //创建数据源  工厂模式--> 创建对象
             dataSource = BasicDataSourceFactory.createDataSource(properties);


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取连接
    public static Connection getConnection() throws SQLException {
            return dataSource.getConnection();
    }

    //释放资源
    public static void release(Connection conn, Statement st, ResultSet rs){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(st!=null){
            try {
                st.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }

        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

对数据库的插入操作测试
```java
public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement statement = null;

        try {
            connection = JdbcUtils_dbcp.getConnection();

            String sql = "INSERT INTO users(`id`,`NAME`,`PASSWORD`,`email`,`birthday`) VALUES(?,?,?,?,?)";

            statement = connection.prepareStatement(sql);

            //手动给参数赋值
            statement.setInt(1,4);
            statement.setString(2,"zhenzhen");
            statement.setString(3,"132321456");
            statement.setString(4,"2267253192@qq.com");
            statement.setDate(5,new java.sql.Date(new Date().getTime()));

            int i = statement.executeUpdate();
            if(i>0){
                System.out.println("插入成功~");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JdbcUtils_dbcp.release(connection,statement,null);
        }
    }

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值