JDBC之DBUtils

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

  • org.apache.commons.dbutils.QueryRunner
  • org.apache.commons.dbutils.ResultSetHandler
  • 工具类
    • org.apache.commons.dbutils.DbUtils

DbUtils :提供如关闭连接、装载JDBC驱动程序等常规工作的工具类,里面的所有方法都是静态的。主要方法如下:

  • public static void close(…) throws java.sql.SQLException: DbUtils类提供了三个重载的关闭方法。这些方法检查所提供的参数是不是NULL,如果不是的话,它们就关闭Connection、Statement和ResultSet。
  • public static void closeQuietly(…): 这一类方法不仅能在Connection、Statement和ResultSet为NULL情况下避免关闭,还能隐藏一些在程序中抛出的SQLEeception。
  • public static void commitAndCloseQuietly(Connection conn): 用来提交连接,然后关闭连接,并且在关闭连接时不抛出SQL异常。
  • public static boolean loadDriver(java.lang.String driverClassName):这一方装载并注册JDBC驱动程序,如果成功就返回true。使用该方法,你不需要捕捉这个异常ClassNotFoundException。

QueryRunner类提供了两个构造方法:

  • 默认的构造方法
  • 需要一个 javax.sql.DataSource 来作参数的构造方法。
  • public Object query(Connection conn, String sql, Object[] params, ResultSetHandler rsh) throws SQLException:执行一个查询操作,在这个查询中,对象数组中的每个元素值被用来作为查询语句的置换参数。该方法会自行处理 PreparedStatement 和 ResultSet 的创建和关闭。
  • public Object query(String sql, Object[] params, ResultSetHandler rsh) throws SQLException: 几乎与第一种方法一样;唯一的不同在于它不将数据库连接提供给方法,并且它是从提供给构造方法的数据源(DataSource) 或使用的setDataSource 方法中重新获得 Connection。
  • public Object query(Connection conn, String sql, ResultSetHandler rsh) throws SQLException : 执行一个不需要置换参数的查询操作。
  • public int update(Connection conn, String sql, Object[] params) throws SQLException:用来执行一个更新(插入、更新或删除)操作。
  • public int update(Connection conn, String sql) throws SQLException:用来执行一个不需要置换参数的更新操作。
例子:
/**
	 * 测试QurryRunner 类的 update 方法
	 * 
	 * @throws Exception
	 */
//	@Test
	public void testQueryRunnerUpdate() throws Exception {
		// 1. 创建 QueryRunner 的实现类
		QueryRunner queryRunner = new QueryRunner();
		// 2. 使用其 update 方法
		String sql = "DELETE FROM customers WHERE id = 34";
		Connection connection = null;
		try {
			connection = JDBCTools.getConnection();

			queryRunner.update(connection, sql);
		} catch (Exception e) {
			e.printStackTrace();// TODO: handle exception
		} finally {
			JDBCTools.release(null, null, connection);
		}

	}
/**
	 * QueryRunner 的 query 方法的返回值取决于其 ResultSetHandler 参数的 handle 方法的返回值
	 */
	// @Test
	public void testQuery() {
		Connection connection = null;

		try {
			connection = JDBCTools.getConnection();
			String sql = "SELECT id,name,email,birth FROM customers";
			Object obj = queryRunner.query(connection, sql, new MyResultSetHandler());
			System.out.println(obj);
		} catch (Exception e) {
			e.printStackTrace();// TODO: handle exception
		} finally {
			JDBCTools.release(null, null, connection);
		}

	}

ResultSetHandle接口:

  • 该接口用于处理 java.sql.ResultSet,将数据按要求转换为另一种形式。
  • ResultSetHandler 接口提供了一个单独的方法:Object handle (java.sql.ResultSet .rs)。
  • ArrayHandler:把结果集中的第一行数据转成对象数组。
  • ArrayListHandler:把结果集中的每一行数据都转成一个数组,再存放到List中。
  • BeanHandler:将结果集中的第一行数据封装到一个对应的JavaBean实例中。
  • BeanListHandler:将结果集中的每一行数据都封装到一个对应的JavaBean实例中,存放到List里。
  • ColumnListHandler:将结果集中某一列的数据存放到List中。
  • KeyedHandler(name):将结果集中的每一行数据都封装到一个Map里,再把这些map再存到一个map里,其key为指定的key。
  • MapHandler:将结果集中的第一行数据封装到一个Map里,key是列名,value就是对应的值。
  • MapListHandler:将结果集中的每一行数据都封装到一个Map里,然后再存放到List

QueryRunner queryRunner = new QueryRunner();

	class MyResultSetHandler implements ResultSetHandler {

		@Override
		public Object handle(ResultSet rs) throws SQLException {
			// System.out.println("handle...");
			// return null;

			List<Customer> customers = new ArrayList<>();

			while (rs.next()) {
				Integer id = rs.getInt(1);
				String name = rs.getString(2);
				String email = rs.getString(3);
				Date birth = rs.getDate(4);
				Customer customer = new Customer(id, name, email, (java.sql.Date) birth);
				customers.add(customer);
			}
			return customers;
		}

	}

	/**
	 * BeanHandler : 把结果集的第一条记录转为创建 BeanHandle 对象时传入的 CLass 参数对应的对象.
	 */
//	@Test
	public void testBeanHanlder() {
		Connection connection = null;

		try {
			connection = JDBCTools.getConnection();
			String sql = "SELECT id,name,email ,birth FROM customers WHERE id = ?";
			Customer customer = queryRunner.query(connection, sql, new BeanHandler<>(Customer.class), 33);
			System.out.println(customer);
		} catch (Exception e) {
			e.printStackTrace();// TODO: handle exception
		} finally {
			JDBCTools.release(null, null, connection);
		}
	}
	/**
	 * BeanListHandler : 把结果集转为一个 List , 该 List 不为 null 但可能为空集合(size() 方法返回0) 若 SQL
	 * 语句能够查询到记录 , List 中存放创建 BeanListHandler 传入的 Class 对象对应的对象 .
	 */
	// @Test
	public void testBeanListHandler() {
		Connection connection = null;

		try {
			connection = JDBCTools.getConnection();
			String sql = "SELECT id,name,email ,birth FROM customers WHERE id < ?";
			List<Customer> customers = queryRunner.query(connection, sql, new BeanListHandler<>(Customer.class), 33);
			System.out.println(customers);
		} catch (Exception e) {
			e.printStackTrace();// TODO: handle exception
		} finally {
			JDBCTools.release(null, null, connection);
		}
	}
	
	/**
	 * MapHandler : 返回 SQL 对应的第一条记录对应的 Map 对象 . 
	 * 键: SQl 查的列名 (不是列的别名) 键 : 列的值
	 */
//	@Test
	public void testMapHandler() {
		Connection connection = null;

		try {
			connection = JDBCTools.getConnection();
			String sql = "SELECT id,name,email ,birth FROM customers WHERE id < ?";
			Map<String, Object> customers = queryRunner.query(connection, sql, new MapHandler(), 33);
			System.out.println(customers);
		} catch (Exception e) {
			e.printStackTrace();// TODO: handle exception
		} finally {
			JDBCTools.release(null, null, connection);
		}
	}

/**
	 * ScalarHandler : 把结果集转为一个数值(可以使任意基本数据类型和字符串)
	 */
	@Test
	public void testScalarHander() {
		Connection connection = null;

		try {
			connection = JDBCTools.getConnection();
			String sql = "SELECT name FROM customers WHERE id = ?";
			Object customers = queryRunner.query(connection, sql, new ScalarHandler(), 33);
			System.out.println(customers);
		} catch (Exception e) {
			e.printStackTrace();// TODO: handle exception
		} finally {
			JDBCTools.release(null, null, connection);
		}
	}
	
//	@Test
	public void testMapListHandler() {
		Connection connection = null;

		try {
			connection = JDBCTools.getConnection();
			String sql = "SELECT id,name,email ,birth FROM customers WHERE id < ?";
			List<Map<String, Object>> customers = queryRunner.query(connection, sql, new MapListHandler(), 33);
			System.out.println(customers);
		} catch (Exception e) {
			e.printStackTrace();// TODO: handle exception
		} finally {
			JDBCTools.release(null, null, connection);
		}
	}

猜你喜欢

转载自blog.csdn.net/weixin_37590761/article/details/86495756