zoukankan      html  css  js  c++  java
  • java--DBUtils和连接池

    DBUtils

    一、DBUtils的使用

          DBUtils就是JDBC的简化开发工具包需要项目导入commons-dbutils-1.6.jar才能够正常使用DBUtils工具。如果只使用JDBC进行开发,我们会发现冗余代码过多,为了简化JDBC开发,本案例我们讲采用apache commons组件一个成员:DBUtils。

     

    二、DBUtils概述

    DBUtilsjava编程中的数据库操作实用工具,小巧简单实用。DBUtils封装了对JDBC的操作,简化了JDBC操作,可以少写代码。

    Dbutils三个核心功能介绍:

      1.QueryRunner中提供对sql语句操作的API.

      2.ResultSetHandler接口,用于定义select操作后,怎样封装结果集.

      3. DbUtils类,它就是一个工具类,定义了关闭资源与事务处理的方法

    三、QueryRunner核心类

    1.update(Connection conn, String sql, Object... params) ,用来完成表数据的增加、删除、更新操作

    2.query(Connection conn, String sql, ResultSetHandler<T> rsh, Object... params) ,用来完成表数据的查询操作

    四、QueryRunner实现添加、更新、删除操作

     //添加
        public void addProduct() throws SQLException{
            Connection conn=JDBCUtils.getConn();
            QueryRunner qr=new QueryRunner();
            String sql="insert into product(pid,pname) values(?,?)";
            Object[] obj={"1234567","iphoneXS"};
            qr.update(conn, sql,obj);
            DbUtils.closeQuietly(conn);
        }
    //删除
        public void deleteProduct() throws SQLException{
            Connection conn=JDBCUtils.getConn();
            QueryRunner qr=new QueryRunner();
            String sql="delete from product where pname=? ";
            Object[] obj={"qwdqw"};
            qr.update(conn,sql, obj);
            DbUtils.closeQuietly(conn);
        }
    //更新
        public void editProduct() throws SQLException{
            Connection conn=JDBCUtils.getConn();
            QueryRunner qr=new QueryRunner();
            String sql="update product set pname=? where pid=?";
            Object[] obj={"vivoX10","1234567"};
            qr.update(conn, sql,obj);
            DbUtils.closeQuietly(conn);
        }    

    五、QueryRunner实现查询操作

    ResultSetHandler结果集处理类

    ArrayHandler

    将结果集中的第一条记录封装到一个Object[]数组中,数组中的每一个元素就是这条记录中的每一个字段的值

    ArrayListHandler

    将结果集中的每一条记录都封装到一个Object[]数组中,将这些数组在封装到List集合中。

    BeanHandler

    将结果集中第一条记录封装到一个指定的javaBean中。javabean就是类

    BeanListHandler

    将结果集中每一条记录封装到指定的javaBean中,将这些javaBean在封装到List集合中

    ColumnListHandler

    将结果集中指定的列的字段值,封装到一个List集合中

    ScalarHandler

    它是用于单数据。例如select count(*) from 表操作。

    MapHandler

    将结果集第一行封装到Map集合中,Key 列名, Value 该列数据

    MapListHandler

    将结果集第一行封装到Map集合中,Key 列名, Value 该列数据,Map集合存储到List集合

    注:JavaBean就是一个类,在开发中常用封装数据。具有如下特性

    1. 需要实现接口:java.io.Serializable ,通常实现接口这步骤省略了,不会影响程序。
    2. 提供私有字段:private 类型 字段名;
    3. 提供getter/setter方法:
    4. 提供无参构造

    代码实现: 

     1    //ArrayHandler
     2     //将结果集中的第一行数据封装到Object[]中
     3     public void select1() throws SQLException{
     4         Connection conn=JDBCUtils.getConn();
     5         QueryRunner qr=new QueryRunner();
     6         String sql="select * from product";
     7         Object[] obj=qr.query(conn,sql, new ArrayHandler());
     8         for(Object o:obj){
     9             System.out.println(o);
    10         }
    11         DbUtils.closeQuietly(conn);
    12     }
    13     //ArrayListHandler
    14     //将结果集中的每一行都封装到Object[]中,然后将每一个Object数组封装到一个List集合中
    15     public void select2() throws SQLException{
    16         Connection conn=JDBCUtils.getConn();
    17         QueryRunner qr=new QueryRunner();
    18         String sql="select * from product";
    19         List<Object[]> list=qr.query(conn,sql, new ArrayListHandler());
    20         for(Object[] obj:list){
    21             for(Object o:obj){
    22                 System.out.println(o+"	");
    23             }
    24             System.out.println();
    25         }
    26         DbUtils.closeQuietly(conn);
    27     }
    28     //BeanHandler
    29     //前提:JavaBean必须有空参构造和set方法
    30     //将结果集中的第一条记录封装到指定的JavaBean中
    31     public void select3() throws SQLException{
    32         QueryRunner qr=new QueryRunner();
    33         Connection conn=JDBCUtils.getConn();
    34         String sql="select * from product";
    35         Product product=qr.query(conn, sql,new BeanHandler<Product>(Product.class));
    36         System.out.println(product);
    37         DbUtils.closeQuietly(conn);
    38     }
    39     //BeanListHandler
    40     //将结果集中每一条记录封装到指定的javaBean中,将这些javaBean在封装到List集合中
    41     public void select4() throws SQLException{
    42         QueryRunner qr=new QueryRunner();
    43         Connection conn=JDBCUtils.getConn();
    44         String sql="select * from product";
    45         List<Product> list=qr.query(conn, sql,new BeanListHandler<Product>(Product.class));
    46         for(Product p:list){
    47             System.out.println(p);
    48         }
    49         DbUtils.closeQuietly(conn);
    50     }
    51     //ColumnListHandler
    52     //将结果集中指定的列的字段值,封装到一个List集合中
    53     public void select5()throws SQLException{
    54         QueryRunner qr=new QueryRunner();
    55         Connection conn=JDBCUtils.getConn();
    56         String sql="select * from product";
    57         List<String> list=qr.query(conn, sql,new ColumnListHandler<String>("pname"));
    58         for(String s:list){
    59             System.out.println(s);
    60         }
    61         DbUtils.closeQuietly(conn);
    62     }
    63     //ScalarHandler
    64     //它是用于单数据。例如select count(*) from 表操作。
    65     public void select6()throws SQLException{
    66         QueryRunner qr=new QueryRunner();
    67         Connection conn=JDBCUtils.getConn();
    68         String sql="select count(*) from product";
    69         Long count=qr.query(conn, sql,new ScalarHandler<Long>());
    70         System.out.println(count);
    71         DbUtils.closeQuietly(conn);
    72     }
    73     //MapHandler
    74     //将结果集第一行封装到Map集合中,Key 列名, Value 该列数据
    75     public void select7()throws SQLException{
    76         QueryRunner qr=new QueryRunner();
    77         Connection conn=JDBCUtils.getConn();
    78         String sql="select count(*) from product";
    79         Map<String,Object> map=qr.query(conn, sql,new MapHandler());
    80         Set<Map.Entry<String,Object>> set=map.entrySet();
    81         for(Map.Entry<String,Object> entry: set){
    82             System.out.println(entry.getKey()+"..."+entry.getValue());
    83         }
    84         DbUtils.closeQuietly(conn);
    85     }
    86     //MapListHandler
    87     //将结果集第一行封装到Map集合中,Key 列名, Value 该列数据,Map集合存储到List集合
    88     public void select8()throws SQLException{
    89         QueryRunner qr=new QueryRunner(DButils.getDataSource());
    90         //Connection conn=JDBCUtils.getConn();
    91         String sql="select count(*) from product";
    92         List<Map<String,Object>> list=qr.query(sql,new MapListHandler());
    93         for(Map<String,Object> map:list){
    94             Set<Map.Entry<String,Object>> set=map.entrySet();
    95             for(Map.Entry<String,Object> entry: set){
    96                 System.out.println(entry.getKey()+"..."+entry.getValue());
    97             }
    98         }
    99     }

      

    连接池 

    一、连接池概述

      用池来管理Connection,这样可以重复使用Connection。有了池,所以我们就不用自己来创建Connection,而是通过池来获取Connection对象。当使用完Connection后,调用Connectionclose()方法也不会真的关闭Connection,而是把Connection“归还”给池。池就可以再利用这个Connection对象了。

    规范:

    Java为数据库连接池提供了公共的接口:javax.sql.DataSource,各个厂商需要让自己的连接池实现这个接口。这样应用程序可以方便的切换不同厂商的连接池!

    常见的连接池:DBCPC3P0 

    二、DBCP连接池

    1.使用:导包

     2.编写工具类

     1 package com.oracle.tools;
     2 
     3 import java.sql.Connection;
     4 import java.sql.SQLException;
     5 
     6 import javax.sql.DataSource;
     7 
     8 import org.apache.commons.dbcp.BasicDataSource;
     9 
    10 
    11 public class DButils {
    12     public static final String DRIVER = "com.mysql.jdbc.Driver";
    13     public static final String URL = "jdbc:mysql://localhost:3306/bank";
    14     public static final String USERNAME = "root";
    15     public static final String PASSWORD = "123456";
    16     /*
    17      * 创建连接池BasicDataSource
    18      */
    19     public static BasicDataSource dataSource = new BasicDataSource();
    20     public static ThreadLocal<Connection> tl=new ThreadLocal<Connection>();
    21     //静态代码块
    22     static {
    23         //对连接池对象 进行基本的配置
    24         dataSource.setDriverClassName(DRIVER); // 这是要连接的数据库的驱动
    25         dataSource.setUrl(URL); //指定要连接的数据库地址
    26         dataSource.setUsername(USERNAME); //指定要连接数据的用户名
    27         dataSource.setPassword(PASSWORD); //指定要连接数据的密码
    28     }
    29     /*
    30      * 返回连接池对象
    31      */
    32     //获取当前线程上的连接
    33     public static Connection getCurrentConnection(){
    34         Connection conn=tl.get();
    35         if(conn==null){
    36             conn=getConn();
    37             tl.set(conn);
    38         }
    39         return conn;
    40     }
    41     //开启事务的方法
    42     public static void start(){
    43         try {
    44             getCurrentConnection().setAutoCommit(false);
    45         } catch (SQLException e) {
    46             // TODO Auto-generated catch block
    47             e.printStackTrace();
    48         }
    49     }
    50     //提交事务的方法
    51     public static void commit(){
    52         try {
    53             getCurrentConnection().commit();
    54         } catch (SQLException e) {
    55             // TODO Auto-generated catch block
    56             e.printStackTrace();
    57         }
    58     }
    59     //回滚事务方法
    60     public static void rollback(){
    61         try {
    62             getCurrentConnection().rollback();
    63         } catch (SQLException e) {
    64             // TODO Auto-generated catch block
    65             e.printStackTrace();
    66         }
    67     }
    68     //从连接池里获取一个新连接
    69     public static DataSource getDataSource(){
    70         return dataSource;
    71     }
    72     public static Connection getConn(){
    73         Connection conn=null;
    74         try {
    75              conn=dataSource.getConnection();
    76         } catch (SQLException e) {
    77             // TODO Auto-generated catch block
    78             e.printStackTrace();
    79         }
    80         return conn;
    81     }
    82 }

     3.测试:

     1 //MapListHandler
     2     //将结果集第一行封装到Map集合中,Key 列名, Value 该列数据,Map集合存储到List集合
     3     public void select8()throws SQLException{
     4         QueryRunner qr=new QueryRunner(DButils.getDataSource());//有参构造
     5         //Connection conn=JDBCUtils.getConn();
     6         String sql="select count(*) from product";
     7         List<Map<String,Object>> list=qr.query(sql,new MapListHandler());
     8         for(Map<String,Object> map:list){
     9             Set<Map.Entry<String,Object>> set=map.entrySet();
    10             for(Map.Entry<String,Object> entry: set){
    11                 System.out.println(entry.getKey()+"..."+entry.getValue());
    12             }
    13         }
    14     }

    4.常见配置项(了解)

    参考文档:http://commons.apache.org/proper/commons-dbcp/configuration.html

    分类

    属性

    描述

    必须项

    driverClassName

    数据库驱动名称

    url

    数据库的地址

    username

    用户名

    password

    密码

    基本项(扩展)

    maxActive

    最大连接数量

    minIdle

    最小空闲连接

    maxIdle

    最大空闲连接

    initialSize

    连接池中初始化多少个Connection连接对象

     

    扩展项

    maxWait

    超时等待时间以毫秒为单位 1000等于1

  • 相关阅读:
    split 过滤空的元素
    Python内置函数(65)——staticmethod
    Python内置函数(64)——classmethod
    Python内置函数(63)——property
    Python内置函数(62)——exec
    Python内置函数(61)——eval
    Js里头的对象字面量
    Js中的prototype的用法二
    Js中的prototype的用法一
    Mxgraph使用总结二
  • 原文地址:https://www.cnblogs.com/-dashu/p/9650143.html
Copyright © 2011-2022 走看看