数据库连接池

前言

   在前面我们每次操作数据库时,都是由程序帮我们创建一个跟数据库进行连接的对象并在每次使用完毕后将连接对象销毁来进行操作的。但是这样会浪费资源,所以为了避免资源的浪费我们可以创建一个连接池,也就是一个装有连接的容器。当我们想要使用的时候,就可以直接从连接池中来获取一个用完之后将其归还回去,以达到对jdbc的优化。

数据库连接池使用演示

准备工作

   打开IDEA,新建一个项目,在项目下创建一个lib文件夹,将C3P0的jar包(点此下载提取码:9jrm)复制到lib目录下,然后选中该jar包,右键选择Add to Library,在弹出的窗口中点击确定即可。

C3P0连接池使用演示代码如下:

    //手动设置连接池
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try{
            //创建连接池
            ComboPooledDataSource dataSource = new ComboPooledDataSource();
            //设置连接池的参数
            dataSource.setDriverClass("com.mysql.jdbc.Driver");
            dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/dbbook");
            dataSource.setUser("root");
            dataSource.setPassword("123456");
            dataSource.setMinPoolSize(20);//设置最大连接数
            dataSource.setInitialPoolSize(5);//设置初始化时连接池中的连接数
            //获得连接
            conn = dataSource.getConnection();
            //编写SQL语句
            String sql = "select * from books";
            //预编译SQL语句
            pstmt = conn.prepareStatement(sql);
            //执行SQL语句
            rs = pstmt.executeQuery();
            while(rs.next()){
                int id = rs.getInt("id");//单条记录中的id字段
                String name = rs.getString("name");//单条记录中的name字段
                double price = rs.getDouble("price");//单条记录中的price字段
                String author = rs.getString("author");//单条记录中的author字段
                String type = rs.getString("chuBanShe");//单条记录中的chuBanShe字段
                int num = rs.getInt("counts");//单条记录中的counts字段

                System.out.println(id + " " + name + " " + price + " " + author + " " + type + " " + num);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //归还资源
            JDBCtest.releaseResources(rs,pstmt,conn);
        }
    }

说明:releaseResources(rs,pstmt,conn)方法的具体实现参考我之前的文章

posted @ 2020-03-02 16:38  Alex-jzw  阅读(182)  评论(0)    收藏  举报