Java操作数据库方式二DBCP使用详解

##概述

DBCP的全称是:DataBase connection pool,翻译是:数据库连接池。

Java操作数据库方式一JDBC使用详解中说到直接使用JDBC非常消耗资源。为了避免频繁关闭链接数据库,所以出现了DBCP。

DBCP的工作原理是:首先通过连接池预先同数据库建立一些连接,放在内存中,应用程序需要建立数据库连接时直接到连接池中取出,用完后再放回去,从而避免繁关闭链接数据库,减少资源的消耗。

DBCP是 apache 的一个开源工具。

##准备工作

在使用JDBC连接数据库之前,首先要有数据库,数据库要创建表。我的数据库信息如下:

  1. 数据库类型:MySql。
  2. 数据库名字:xia。
  3. 用户名:root。
  4. 密码:root.

##开发环境

  1. 操作系统:MACOS。
  2. 开发工具:IntelliJ IDEA。
  3. Java版本:jdk1.7。
  4. 使用maven管理jar包。

##正式开发

一,在pom.xml文件中引入需要jar的依赖

       <!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/commons-dbutils/commons-dbutils -->
        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.4</version>
        </dependency>

二,得到DataSource对象

public class DBCPUtils {

    private static BasicDataSource dataSource;

    static {
        dataSource = new BasicDataSource();
        //基本设置
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/xia");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        //高级设置
        dataSource.setInitialSize(10);//初始化连接
        dataSource.setMinIdle(5);//最小空闲连接
        dataSource.setMaxIdle(20);//最大空闲连接
        dataSource.setMaxActive(50);//最大连接数量
        dataSource.setMaxWait(1000);//超时等待时间以毫秒为单位
    }

    /**
     * 获取DataSource对象
     * @return
     */
    public static DataSource getDataSource() {
        return dataSource;
    }
}

三,插入操作

public static boolean insertStudent(Student student) {
        try {
            //1,得到dataSource对象,
            DataSource dataSource = DBCPUtils.getDataSource();
            //2,得到QueryRunner对象
            QueryRunner queryRunner = new QueryRunner(dataSource);
            //3,执行插入操作sql
            queryRunner.update("insert into student (name,age) values(?,?)", student.getName(), student.getAge());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

四,根据id查找单个对象

public static Student selectStudent(int id) {
        try {
            //1,得到dataSource对象,
            DataSource dataSource = DBCPUtils.getDataSource();
            //2,得到QueryRunner对象
            QueryRunner queryRunner = new QueryRunner(dataSource);
            //3,执行查询作sql
            Student student = queryRunner.query("select id,name,age from student where id=?", new BeanHandler<>(Student.class), id);
            return student;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

五,根据其他条件得到对象集合

public static List<Student> selectUserList(int age) {
        try {
            //1,得到dataSource对象,
            DataSource dataSource = DBCPUtils.getDataSource();
            //2,得到QueryRunner对象
            QueryRunner queryRunner = new QueryRunner(dataSource);
            //3,执行查询作sql
            List<Student> studentList = queryRunner.query("select id,name,age from student where age=?", new BeanListHandler<>(Student.class), age);
            return studentList;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

六,更新操作

public static boolean updateStudent(Student student) {
        try {
            //1,得到dataSource对象,
            DataSource dataSource = DBCPUtils.getDataSource();
            //2,得到QueryRunner对象
            QueryRunner queryRunner = new QueryRunner(dataSource);
            //3,执行更新操作sql
            queryRunner.update("update student set age = ? where id = ?", student.getAge(), student.getId());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

七,删除操作

public static boolean deleteStudent(int id) {
        try {
            //1,得到dataSource对象,
            DataSource dataSource = DBCPUtils.getDataSource();
            //2,得到QueryRunner对象
            QueryRunner queryRunner = new QueryRunner(dataSource);
            //3,执行删除操作sql
            queryRunner.update("delete from student where id = ?", id);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

##使用配置文件配置数据库参数

在实际开发中我们通常创建一个properties配置文件,然后把数据库参数都放在配置文件中,这样便于数据库参数的管理,当数据库参数变化时可以快速找到配置文件然后进行修改。

在resource目录下创建dbcpconfig.properties文件,文件目录位置如下:


文件内容如下:

#连接设置
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/xia
username=root
password=root

#初始化连接
initialSize=10
#最大连接数量
maxActive=50
#最大空闲连接 
maxIdle=20
#最小空闲连接
minIdle=5
此时得到DataSource对象的代码如下:
public class DBCPUtils {
    private static DataSource dataSource;
    static {

        try {
            InputStream in = DBCPUtils.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
            Properties props = new Properties();
            props.load(in);
            dataSource = BasicDataSourceFactory.createDataSource(props);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ExceptionInInitializerError(e);
        }
    }
    /**
     * 获取DataSource对象
     * @return
     */
    public static DataSource getDataSource() {
        return dataSource;
    }
}
其他增删改成操作的代码依旧与上面同。

##总结

一,使用DBCP的重点是获取DataSource对象,然后再创建QueryRunner对象,然后就可以进行增删改查操作。
二,使用DBCP不仅可以节约资源,而且可以直接将查询结果封装成对象,方便使用。

三,在实际开发中建议使用properties配置文件。











猜你喜欢

转载自blog.csdn.net/fightingxia/article/details/80717012
今日推荐