【数据库连接池&DBUtils】

数据库连接池

  • 实际开发中“获得连接”或“释放资源”是非常消耗系统资源的两个过程,为了解决此类性能问题,通常情况我们采用连接池技术,来共享连接Connection。这样我们就不需要每次都创建连接、释放连接了,这些操作都交给了连接池.
  • 用池来管理Connection,这样可以重复使用Connection。 当使用完Connection后,调用Connection的close()方法也不会真的关闭Connection,而是把Connection“归还”给池。
  • Java为数据库连接池提供了公共的接口:javax.sql.DataSource,各个厂商需要让自己的连接池实现这个接口。这样应用程序可以方便的切换不同厂商的连接池!
  • 常见的连接池有 DBCP连接池, C3P0连接池, Druid连接池,
    在这里插入图片描述

DBCP连接池

DBCP也是一个开源的连接池,是Apache成员之一,在企业开发中也比较常见,tomcat内置的连接池。

导入 jar包
  1. 将这两个 jar包添加到 myJar文件夹中 (jar包在资料里的软件文件夹中)
    在这里插入图片描述
  2. 添加myJar库 到项目的依赖中
    在这里插入图片描述
编写工具类
public class DPCPUtils {
    //1.定义常量 保存数据库连接的相关信息
    private static final String DRIVER_NAME = "com.mysql.jdbc.Driver";
    private static final String URL = "jdbc:mysql://localhost:3306/db4?characterEncoding=utf-8";
    private static final String USER = "root";
    private static final String PASSWORD = "123456";

    //2.创建连接池对象 (有DBCP提供的实现类)
    private static BasicDataSource dataSource = new BasicDataSource();

    //3.使用静态代码块进行配置
    static {
        dataSource.setDriverClassName(DRIVER_NAME);
        dataSource.setUrl(URL);
        dataSource.setUsername(USER);
        dataSource.setPassword(PASSWORD);
    }

    //4.获取连接的方法
    public static Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    //5.释放资源方法
    public static void close(Connection connection, Statement statement) {
        if (statement != null && connection != null) {
            try {
                statement.close();
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(Connection connection, Statement statement, ResultSet resultSet) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        close(connection, statement);
    }
}
常见配置项
属性描述
driverClassName数据库驱动名称
url数据库地址
username用户名
password密码
maxActive最大连接数量
maxIdle最大空闲连接
minIdle最小空闲连接
initialSize初始化连接

C3P0连接池

C3P0是一个开源的JDBC连接池,支持JDBC3规范和JDBC2的标准扩展。目前使用它的开源项目有Hibernate、Spring等。

导入 jar包及配置文件
  1. 将jar包 复制到myJar文件夹即可,IDEA会自动导入
    在这里插入图片描述
  2. 导入配置文件 c3p0-config.xml
<c3p0-config>
  
  <!--默认配置-->
    <default-config>  
	
		<!-- initialPoolSize:初始化时获取三个连接,
			  取值应在minPoolSize与maxPoolSize之间。 --> 
        <property name="initialPoolSize">3</property>  
		
		<!-- maxIdleTime:最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。-->
        <property name="maxIdleTime">60</property>  
		
		<!-- maxPoolSize:连接池中保留的最大连接数 -->
        <property name="maxPoolSize">100</property>  
		<!-- minPoolSize: 连接池中保留的最小连接数 -->
        <property name="minPoolSize">10</property>  
		
    </default-config>  
  
   <!--配置连接池mysql-->

    <named-config name="mysql">
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/db5?characterEncoding=UTF-8</property>
        <property name="user">root</property>
        <property name="password">123456</property>
        <property name="initialPoolSize">10</property>
        <property name="maxIdleTime">30</property>
        <property name="maxPoolSize">100</property>
        <property name="minPoolSize">10</property>
    </named-config>
    <!--配置连接池2,可以配置多个-->

</c3p0-config>

c3p0-config.xml 文件名不可更改
直接放到src下,也可以放到到资源文件夹中
3. 在项目下创建一个resource文件夹(专门存放资源文件)
在这里插入图片描述

  1. 选择文件夹,右键 将resource文件夹指定为资源文件夹
    在这里插入图片描述

  2. 将文件放在resource目录下即可,创建连接池对象的时候会去加载这个配置文件
    在这里插入图片描述

编写C3P0工具类
public class C3P0Utils {
    //1.创建连接池对象 C3P0对DataSource接口的实现类
    //使用的配置是 配置文件中的默认配置
    //public static ComboPooledDataSource dataSource = new ComboPooledDataSource();

    //使用指定的配置
    public static ComboPooledDataSource dataSource = new ComboPooledDataSource("mysql");

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

    //释放资源
    public static void close(Connection con, Statement statement){
        if(con != null && statement != null){
            try {
                statement.close();
                //归还连接
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(Connection con, Statement statement, ResultSet resultSet){
        if(con != null && statement != null && resultSet != null){
            try {
                resultSet.close();
                statement.close();
                //归还连接
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
常见配置

在这里插入图片描述

Druid连接池

Druid(德鲁伊)是阿里巴巴开发的号称为监控而生的数据库连接池,Druid是目前最好的数据库连池。在功能、性能、扩展性方面,都超过其他数据库连接池,同时加入了日志监控,可以很好的监控DB池连接和SQL的执行情况。

导入jar包及配置文件
  1. 导入 jar包
    在这里插入图片描述

  2. 导入配置文件
    在这里插入图片描述

编写Druid工具类
public class DruidUtils {
    //1.定义成员变量
    public static DataSource dataSource;

    //2.静态代码块
    static{
        try {
            //3.创建属性集对象
            Properties p = new Properties();

            //4.加载配置文件 Druid 连接池不能够主动加载配置文件 ,需要指定文件
            InputStream inputStream = DruidUtils.class.getClassLoader().getResourceAsStream("druid.properties");

            //5. 使用Properties对象的 load方法 从字节流中读取配置信息
            p.load(inputStream);

            //6. 通过工厂类获取连接池对象
            dataSource = DruidDataSourceFactory.createDataSource(p);

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

    //获取连接的方法
    public static Connection getConnection(){
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    //获取Druid连接池对象的方法
    public static DataSource getDataSource(){
        return dataSource;
    }
    
    //释放资源
    public static void close(Connection con, Statement statement){
        if(con != null && statement != null){
            try {
                statement.close();
                //归还连接
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(Connection con, Statement statement, ResultSet resultSet){
        if(con != null && statement != null && resultSet != null){
            try {
                resultSet.close();
                statement.close();
                //归还连接
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

DBUtils工具类

  • Commons DbUtils是Apache组织提供的一个对JDBC进行简单封装的开源工具类库,使用它能够简化JDBC应用程序的开发,同时也不会影响程序的性能。
  • DBUtils就是JDBC的简化开发工具包。需要项目导入commons-dbutils-1.6.jar。
    在这里插入图片描述
  • 核心功能
  1. QueryRunner 中提供对sql语句操作的API.
  2. ResultSetHandler接口,用于定义select操作后,怎样封装结果集.
  3. DbUtils类,他就是一个工具类,定义了关闭资源与事务处理相关方法.

表和类之间的关系

  • 整个表可以看做是一个类
  • 表中的一行记录,对应一个类的实例(对象)
  • 表中的一列,对应类中的一个成员属性

JavaBean

JavaBean 就是一个类, 开发中通常用于封装数据,有一下特点:

  1. 需要实现 序列化接口, Serializable (暂时可以省略)
  2. 提供私有字段: private 类型 变量名;
  3. 提供 getter 和 setter
  4. 提供 空参构造
@Data
public class Employee implements Serializable {
    private int eid;

    private String ename;

    private int age;

    private String sex;

    private double salary;

    private Date empdate;

    public Employee() {
    }
}

DBUtils完成 CRUD

QueryRunner核心类
  • 构造方法
    QueryRunner()
    QueryRunner(DataSource ds) ,提供数据源(连接池),DBUtils底层自动维护连接connection
  • 常用方法
    update(Connection conn, String sql, Object… params) ,用来完成表数据的增加、删除、更新操作
    query(Connection conn, String sql, ResultSetHandler rsh, Object… params) ,用来完成表数据的查询操作
QueryRunner的创建
  • 手动模式
//手动方式 创建QueryRunner对象 
QueryRunner qr = new QueryRunner();
  • 自动模式
//自动创建 传入数据库连接池对象 
QueryRunner qr2 = new QueryRunner(DruidUtils.getDataSource());
QueryRunner实现增、删、改操作

核心方法
update(Connection conn, String sql, Object… params)

参数说明
Connection conn数据库连接对象, 自动模式创建QueryRun 可以不传 ,手动模式必须传递
String sql占位符形式的SQL ,使用 ? 号占位符
Object… paramObject类型的 可变参,用来设置占位符上的参数
public class DBUtilsTest {
    @Test
    public void testInsert() {
        // 1.创建QueryRunner 手动模式
        QueryRunner queryRunner = new QueryRunner();
        // 2.编写sql
        String sql = "insert into employee values(?,?,?,?,?,?);";
        Object[] param = {null, "张三", 20, "男", 1000, "2000-06-09"};
        // 3.执行update方法
        Connection connection = DruidUtils.getConnection();
        try {
            queryRunner.update(connection, sql, param);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        // 4.关闭资源
        DbUtils.closeQuietly(connection);
    }

    @Test
    public void testUpdate() {
        // 1.创建QueryRunner对象 自动模式
        QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
        String sql = "update employee set salary = ? where ename = ?;";
        Object[] param = {15000, "张三"};
        try {
        	// 自动模式可以不用传入Connection对象
            queryRunner.update(sql, param);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void testDelete() {
        QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
        String sql = "delete from employee where ename = ?;";
        try {
        	// 只有一个参数可以不用创建数组
            queryRunner.update(sql, "张三");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
QueryRunner实现查询操作
ResultSetHandler接口

ResultSetHandler可以对查询出来的ResultSet结果集进行处理,达到一些业务上的需求。

ResultSetHandler 结果集处理类
ResultSetHandler实现类说明
ArrayHandler将结果集中的第一条记录封装到一个Object[]数组中,数组中的每一个元素就是这条记录中的每一个字段的值
ArrayListHandler将结果集中的每一条记录都封装到一个Object[]数组中,将这些数组在封装到List集合中。
BeanHandler将结果集中第一条记录封装到一个指定的javaBean中.
BeanListHandler将结果集中每一条记录封装到指定的javaBean中,再将这些javaBean在封装到List集合中
ColumnListHandler将结果集中指定的列的字段值,封装到一个List集合中
KeyedHandler将结果集中每一条记录封装到Map<String,Object>,在将这个map集合做为另一个Map的value,另一个Map集合的key是指定的字段的值。
MapHandler将结果集中第一条记录封装到了Map<String,Object>集合中,key就是字段名称,value就是字段值
MapListHandler将结果集中每一条记录封装到了Map<String,Object>集合中,key就是字段名称,value就是字段值,在将这些Map封装到List集合中。
ScalarHandler它是用于封装单个数据。例如 select count(*) from 表操作。
ResultSetHandler 常用实现类测试
  • QueryRunner的查询方法
  • query方法的返回值都是泛型,具体的返回值类型,会根据结果集的处理方式,发生变化
方法说明
query(String sql, handler ,Object[] param)自动模式创建QueryRunner, 执行查询<b
query(Connection con,String sql,handler,Object[] param)手动模式创建QueryRunner, 执行查询
ublic class ResultSetHandlerTest {
    /**
     * 查询id为5的记录,封装到数组中
     */
    @Test
    public void testFindById() throws SQLException {
        QueryRunner queryRunner = new QueryRunner();
        String sql = "select * from employee where eid = ?;";
        Object[] query = queryRunner.query(DruidUtils.getConnection(), sql, new ArrayHandler(), 5);
        System.out.println(Arrays.toString(query));
    }

    /**
     * 查询所有数据,封装到List集合中
     */
    @Test
    public void testFindAll() throws SQLException {
        QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
        String sql = "select * from employee;";
        List<Object[]> query = queryRunner.query(sql, new ArrayListHandler());
        for (Object[] objects : query) {
            System.out.println(Arrays.toString(objects));
        }
    }

    /**
     * 查询id为3的记录,封装到指定JavaBean中
     */
    @Test
    public void testFindByIdJavaBean() throws SQLException {
        QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
        String sql = "select * from employee where eid = ?;";
        Employee query = queryRunner.query(sql, new BeanHandler<>(Employee.class), 3);
        System.out.println(query);
    }

    /**
     * 查询薪资大于 3000 的所员工信息,封装到JavaBean中再封装到List集合中
     */
    @Test
    public void testFindBySalary() throws SQLException {
        QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
        String sql = "select * from employee where salary > ?;";
        List<Employee> query = queryRunner.query(sql, new BeanListHandler<>(Employee.class), 3000);
        for (Employee employee : query) {
            System.out.println(employee);
        }
    }

    /**
     * 查询姓名是 张百万的员工信息,将结果封装到Map集合中
     */
    @Test
    public void testFindByName() throws SQLException {
        QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
        String sql = "select * from employee where ename = ?;";
        Map<String, Object> query = queryRunner.query(sql, new MapHandler(), "张百万");
        Set<Map.Entry<String, Object>> entries = query.entrySet();
        for (Map.Entry<String, Object> entry : entries) {
            System.out.println(entry.getKey() + ":" + entry.getValue());
        }
    }

    /**
     * 查询所有员工的薪资总额
     */
    @Test
    public void testGetSum() throws SQLException {
        QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
        String sql = "select sum(salary) from employee;";
        Double query = queryRunner.query(sql, new ScalarHandler<>());
        System.out.println(query);
    }
}

数据库批处理

  • 批处理指的是一次操作中执行多条SQL语句,批处理相比于一次一次执行效率会提高很多。
  • 当向数据库中添加大量的数据时,需要用到批处理。
  • Statement和PreparedStatement都支持批处理操作
  1. PreparedStatement的批处理方式:
方法说明
void addBatch()将给定的 SQL 命令添加到此 Statement 对象的当前命令列表中。通过调用方法 executeBatch 可以批量执行此列表中的命令。
int[] executeBatch()每次提交一批命令到数据库中执行,如果所有的命令都成功执行了,那么返回一个数组,这个数组是说明每条命令所影响的行数
  1. mysql 批处理是默认关闭的,所以需要加一个参数才打开mysql 数据库批处理,在url中添加
    rewriteBatchedStatements=true

例如: url=jdbc:mysql://127.0.0.1:3306/db5?characterEncoding=UTF-8&rewriteBatchedStatements=true
向testbatch表中插入1w条数据:

public class TestBatch {
    public static void main(String[] args) throws SQLException {
        Connection connection = DruidUtils.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(
            "insert into testBatch(uname) values(?)");
        for (int i = 0; i < 10000; i++) {
            preparedStatement.setString(1, "小强" + i);
            preparedStatement.addBatch();
        }
        long start = System.currentTimeMillis();
        preparedStatement.executeBatch();
        long end = System.currentTimeMillis();
        System.out.println("插入1万条数据用批处理执行的时间:" + (end - start) + "毫秒"); //91
    }
}

MySql元数据

  • 除了表之外的数据都是元数据,可以分为三类:
  • 查询结果信息: UPDATE 或 DELETE语句 受影响的记录数。
  • 数据库和数据表的信息: 包含了数据库及数据表的结构信息。
  • MySQL服务器信息: 包含了数据库服务器的当前状态,版本号等。

元数据相关的命令介绍

1.查看服务器当前状态

SHOW STATUS;

2.查看MySQl的版本信息

select version();

3.查询表中的详细字段信息

show columns from table_name

4.显示数据表的详细索引信息

show index from table_name;

5.列出所有数据库

show databases;

6.显示当前数据库的所有表

show tables;

7.获取当前的数据库名

select database();

使用JDBC 获取元数据

通过JDBC 也可以获取到元数据,比如数据库的相关信息,或者当我们使用程序查询一个不熟悉的表时, 我们可以通过获取元素据信息,了解表中有多少个字段,字段的名称 和 字段的类型.

元数据类作用
DatabaseMetaData描述数据库的元数据对象
ResultSetMetaData描述结果集的元数据对象
  • 获取元数据对象的方法 : getMetaData ()
  • connection 连接对象, 调用 getMetaData () 方法,获取的是DatabaseMetaData 数据库元数据对象
  • PrepareStatement 预处理对象调用 getMetaData () , 获取的是ResultSetMetaData , 结果集元数据对象
  • DatabaseMetaData的常用方法
方法说明
getURL()获取数据库的URL
getUserName()获取当前数据库的用户名
getDatabaseProductName()获取数据库的产品名称
getDatabaseProductVersion()获取数据的版本号
getDriverName()返回驱动程序的名称
isReadOnly()判断数据库是否只允许只读 true 代表只读
public class TestDataMetadata {
    public static void main(String[] args) throws SQLException {
        Connection connection = DruidUtils.getConnection();
        DatabaseMetaData metaData = connection.getMetaData();
        // 获取数据库的URL
        System.out.println(metaData.getURL()); // jdbc:mysql://127.0.0.1:3306/db5?characterEncoding=UTF-8&rewriteBatchedStatements=true
        // 获取数据库的用户名
        System.out.println(metaData.getUserName()); // root@localhost
        // 获取数据库的产品名称
        System.out.println(metaData.getDatabaseProductName()); // MySQL
        // 获取数据的版本号
        System.out.println(metaData.getDatabaseProductVersion()); //5.7.28-log
        // 返回驱动程序的名称
        System.out.println(metaData.getDriverName()); // MySQL Connector Java
        // 判断数据库是否只允许只读 true 代表只读
        System.out.println(metaData.isReadOnly()); // false
    }
}
  • ResultSetMetaData的常用方法
方法说明
getColumnCount()当前结果集共有多少列
getColumnName(int i)获取指定列号的列名, 参数是整数 从1开始
getColumnTypeName(int i)获取指定列号列的类型, 参数是整数 从1开始
public class TestResultSetMetaData {
    public static void main(String[] args) throws SQLException {
        Connection connection = DruidUtils.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement("select * from employee;");
        ResultSetMetaData metaData = preparedStatement.getMetaData();
        // 当前结果集共有多少列
        System.out.println(metaData.getColumnCount()); // 6
        // 获取指定列号的列名, 参数是整数 从1开始
        System.out.println(metaData.getColumnName(1)); // eid
        // 获取指定列号列的类型, 参数是整数 从1开始
        System.out.println(metaData.getColumnTypeName(1)); // INT

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值