JDBCUtils

封装JDBCUtils工具类

image

package com.offcn.util;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * 负责管理数据库连接的
 * 1.封装连接池对象的创建过程
 * 2.封装从连接池中获取数据库连接对象的过程
 */
public class JdbcUtils {
    private static ComboPooledDataSource dataSource;
    static{
         dataSource = new ComboPooledDataSource();
    }

    public static Connection getConnection(){
        try {
           return dataSource.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return null;
        }
    }
}

dbutils使用

(一)简介

commons-dbutils 是 Apache 组织提供的一个开源 JDBC工具类库,它是对JDBC的简单封装,
学习成本极低,并且使用dbutils能极大简化jdbc编码的工作量,同时也不会影响程序的性能。

(二)作用

DbUtils :提供如关闭连接、装载JDBC驱动程序等常规工作的工具类,里面的所有方法都是静态的。
该包封装了SQL的执行,是线程安全的。
(1)可以实现增、删、改、查、批处理、

(2)考虑了事务处理需要共用Connection。

(3)该类最主要的就是简单化了SQL查询,它与ResultSetHandler组合在一起使用可以完成大部分的数据库操作,能够大大减少编码量。

(三)常用的方法

① 操作:update()
	public int update(Connection conn, String sql, Object... params) throws SQLException:用来执行一个更新(插入、更新或删除)操作。
② 查询:query()
	public Object query(Connection conn, String sql, ResultSetHandler rsh,Object... params) throws SQLException:执行一个查询操作,在这个查询中,对象数组中的每个元素值被用来作为查询语句的置换参数。该方法会自行处理 PreparedStatement 和 ResultSet 的创建和关闭。

注:
	该接口用于处理 java.sql.ResultSet,将数据按要求转换为另一种形式。ResultSetHandler 接口提供了一个单独的方法:Object handle (java.sql.ResultSet rs)该方法的返回值将作为QueryRunner类的query()方法的返回值

方法:
 	ArrayHandler:把结果集中的第一行数据转成对象数组。
 	ArrayListHandler:把结果集中的每一行数据都转成一个数组,再存放到List中。
 	BeanHandler:将结果集中的第一行数据封装到一个对应的JavaBean实例中。
 	BeanListHandler:将结果集中的每一行数据都封装到一个对应的JavaBean实例中,存放到List里。
 	ColumnListHandler:将结果集中某一列的数据存放到List中。
 	MapHandler:将结果集中的第一行数据封装到一个Map里,key是列名,value就是对应的值。
 	MapListHandler:将结果集中的每一行数据都封装到一个Map里,然后再存放到List
    ScalarHandler:返回结果集中第一行第一列的数据,返回类型为object

(四)基本使用

s① 下载导包   commons-dbutils-1.7.jar

http://commons.apache.org/proper/commons-dbutils/


```Java
② 使用
	1 创建核心对象 

QueryRunner qr = new QueryRunner();

② 执行命令 
	int update = qr.update(connection,sql,params); // 执行增删改
	T t = qr.query(connection,sql,new BeanHandler,params);
	List t = qr.query(connection,sql,new BeanListHandler,params);
	Object t = qr.query(connection,sql,new ScalerHandler,params);

代码

package com.offcn.test;

import com.offcn.entity.Goods;
import com.offcn.util.JdbcUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayListHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.junit.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

public class TestHomeWork {

    QueryRunner qr = new QueryRunner();

//    #4.删除商品id为6的商品
    @Test
    public void test4() throws SQLException {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = JdbcUtils.getConnection();
            pstmt = conn.prepareStatement("delete from goods where gid = ?");
            pstmt.setObject(1,6);
            int i = pstmt.executeUpdate();
            System.out.println(i>0?"操作成功":"操作失败");
        } finally {
            pstmt.close();
            conn.close();
        }
    }

//#5.修改商品名称为”华为手机“的价格为6666
    @Test
    public void test5() throws SQLException {
        Connection conn = JdbcUtils.getConnection();
        try {
            qr.update(conn,"update goods set price = ? where gname = ?",6666,"华为手机");
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally{
            conn.close();
        }
    }

//#6.查询商品表中的最大库存量
    @Test
    public void test6() throws SQLException {
        Connection conn = null;
        try {
            conn = JdbcUtils.getConnection();
            Object count = qr.query(conn, "select max(store) from goods", new ScalarHandler<>());
            System.out.println(count);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            conn.close();
        }
    }
//#7.查询商品表中价格在3000-9000的商品信息
    @Test
    public void test7() throws SQLException {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            conn = JdbcUtils.getConnection();
            pstmt = conn.prepareStatement("select * from goods where price between ? and ?");
            pstmt.setObject(1,3000);
            pstmt.setObject(2,9000);
            rs = pstmt.executeQuery();
            while(rs.next()){
                System.out.println("商品名称:"+rs.getString("gname")+"	商品价格:"+
                        rs.getDouble("price")+"	商品库存:"+rs.getInt("store"));
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            rs.close();
            pstmt.close();
            conn.close();
        }
    }
//
//#8.查询商品中的平均价格
@Test
public void test8() throws SQLException {
    Connection conn = null;
    try {
        conn = JdbcUtils.getConnection();
        Object count = qr.query(conn, "select avg(price) from goods", new ScalarHandler<>());
        System.out.println(count);
    } catch (SQLException throwables) {
        throwables.printStackTrace();
    } finally {
        conn.close();
    }
}

//#9.查询每种分类下面的商品数量
@Test
public void test9() throws SQLException {
    Connection conn = null;
    try {
        conn = JdbcUtils.getConnection();
        List<Object[]> list = qr.query(conn, "select cate_id,sum(store) from goods group by  cate_id", new ArrayListHandler());
        for (Object[] objects : list) {
            System.out.println(Arrays.toString(objects));
        }
    } catch (SQLException throwables) {
        throwables.printStackTrace();
    } finally {
        conn.close();
    }
}


//#10. 分页查询商品表,每页显示3条,查询第二页商品信息
    //(页码-1)*每页显示数量,数量
 @Test
public void test10() throws SQLException {
    Connection conn = null;
    try {
        conn = JdbcUtils.getConnection();
        List<Goods> goodsList = qr.query(conn, "select * from goods limit ?,? ", new BeanListHandler<Goods>(Goods.class), 3, 3);
        for (Goods goods : goodsList) {
            System.out.println(goods.getGname());
        }
    } catch (SQLException throwables) {
        throwables.printStackTrace();
    } finally {
        conn.close();
    }
}
//#11. 查询商品信息及商品对应的商品分类名称
@Test
public void test11() throws SQLException {
    Connection conn = null;
    try {
        conn = JdbcUtils.getConnection();
        List<Object[]> list = qr.query(conn, "select g.*,c.cname from goods as g,cate as c where g.cate_id = c.cid", new ArrayListHandler());
        for (Object[] objects: list) {
            System.out.println(Arrays.toString(objects));
        }
    } catch (SQLException throwables) {
        throwables.printStackTrace();
    } finally {
        conn.close();
    }
}

//#12. 查询商品表中最贵的商品信息
@Test
public void test12() throws SQLException {
    Connection conn = null;
    try {
        conn = JdbcUtils.getConnection();
        Goods goods = qr.query(conn, "select * from goods where price = (select max(price) from goods)", new BeanHandler<Goods>(Goods.class));
        System.out.println(goods.getGname()+"	"+goods.getPrice());
    } catch (SQLException throwables) {
        throwables.printStackTrace();
    } finally {
        conn.close();
    }
}

//#13.查询库存量最小的商品信息
@Test
public void test13() throws SQLException {
    Connection conn = null;
    try {
        conn = JdbcUtils.getConnection();
        Goods goods = qr.query(conn, "select * from goods where store = (select min(store) from goods)", new BeanHandler<Goods>(Goods.class));
        System.out.println(goods.getGname()+"	"+goods.getPrice());
    } catch (SQLException throwables) {
        throwables.printStackTrace();
    } finally {
        conn.close();
    }
}

//
//#14. 查询所有商品的商品名称,所属分类名称和库存
    @Test
    public void test14() throws SQLException {
        Connection conn = null;
        try {
            conn = JdbcUtils.getConnection();
            List<Object[]> list = qr.query(conn, "select g.gname,c.cname,g.store from goods as g,cate as c where g.cate_id = c.cid", new ArrayListHandler());
            for (Object[] objects: list) {
                System.out.println(Arrays.toString(objects));
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            conn.close();
        }
    }
}

原文地址:https://www.cnblogs.com/conglingkaishi/p/15232261.html