数据库连接池工具---DbUtils

Posted 夏小弥

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了数据库连接池工具---DbUtils相关的知识,希望对你有一定的参考价值。

DbUtils

DbUtils是基于c3p0来做的,功能很是强大。

首先做一个c3p0的连接池C3p0Pool:

package cn.hncu.c3p0;

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

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

//我们的这个包装,只是为了把c3p0池做成让每个线程(客户端)获得的是同一个连接,方便做b/s框架下的事务
public class C3p0Pool 
	private static DataSource pool;
	private static ThreadLocal<Connection> t=new ThreadLocal<Connection>();
	static 
		pool=new ComboPooledDataSource();
	
	
	public static DataSource getDataSource()
		return pool;
	
	
	public static Connection getConnection() throws SQLException
		Connection con=t.get();
		if (con==null)
			con=pool.getConnection();
			t.set(con);
		
		return con;
	
相关的知识点都写在里代码的注解中了,下面是代码:

package cn.hncu.dbutils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ext.ExtQueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.junit.Test;

import cn.hncu.c3p0.C3p0Pool;

public class DbutilsDemo 
	@Test//原来不使用dbUtils工具的数据库查询代码实现
	public void jdbcQuery() throws Exception
		List<Stud> list=new ArrayList<Stud>();
		Connection con=C3p0Pool.getConnection();
		String sql="select * from stud";
		Statement st=con.createStatement();
		ResultSet rs=st.executeQuery(sql);
		while (rs.next())
			Stud stud=new Stud();
			stud.setId(rs.getString("id"));
			stud.setName(rs.getString("name"));
			stud.setAge(rs.getInt("age"));
			list.add(stud);
		
		System.out.println(list);
	
	
	@Test//使用dbUtils工具的数据库查询代码实现
	public void dbutilsQuery() throws Exception
		QueryRunner run=new QueryRunner(C3p0Pool.getDataSource());
		String sql="select * from stud";
		List<Stud> stud=run.query(sql, new BeanListHandler<Stud>(Stud.class));
		System.out.println(stud);
	
	@Test
	public void dbutilsQuery2() throws Exception
		QueryRunner run=new QueryRunner(C3p0Pool.getDataSource());
		String sql="select * from stud";
		List<Map<String, Object>> stud=run.query(sql, new MapListHandler());
		System.out.println(stud);
	
	
	DbUtils工具的使用演示: 增删改--用update(),  查--用query()方法
	/*
	 CREATE TABLE person(
        id VARCHAR(30) PRIMARY KEY,
        NAME VARCHAR(30),
        address VARCHAR(30),
        age INT
     );
	 */
	@Test
	public void save() throws Exception
		QueryRunner run=new QueryRunner(C3p0Pool.getDataSource());
		//Statement方式
		//run.update("insert into dbutilsperson(id,name,address,age) values('A001','Jack','湖南长沙',22)");
		//PrepareStatement方式
		run.update("insert into dbutilsperson(id,name,address,age) values(?,?,?,?)", "A002","Tom","中国西安",24);//如果参数个数或类型 与 “?”号不匹配,会出异常 
	
	@Test
	public void saveTx() throws Exception
		QueryRunner run=new QueryRunner(C3p0Pool.getDataSource());
		Connection con=C3p0Pool.getConnection();
		try 
			con.setAutoCommit(false);
			//※注意,实现事务功能时,要传入con对象,且多条语句共处一个事务时,要传入同一个con对象。但如果不实现事务功能,可以不传入con对象
			run.update(con, "insert into dbutilsperson(id,name,address,age) values(?,?,?,?)","A003","Tom","浙江杭州",24); 
			run.update(con, "insert into dbutilsperson(id,name,address,age) values(?,?,?,?)","A003","Tom","浙江杭州",24); 
		 catch (Exception e) 
			con.rollback();
			System.out.println("事务回滚了");
		 finally 
			con.setAutoCommit(true);
			con.close();
		
	
	
	//下面演示一下查询的结果集封装功能
	@Test//封装成BeanList
	public void query1() throws Exception
		QueryRunner run=new QueryRunner(C3p0Pool.getDataSource());
		//封装成BeanList: 如果值对象中的属性名和表中的字段名不一致,那么该属性的值返回的是null----解决:采用别名,但是最好不要这样做,在取名字的时候我们就应该要两边保持一致,不要这样子自己坑自己
		//List<Person> persons=run.query("select * from dbutilsperson", new BeanListHandler<Person>(Person.class));//没有采用别名,addr属性为null
		List<Person> persons=run.query("select id,name,address addr,age from dbutilsperson", new BeanListHandler<Person>(Person.class));//用属性名 当  字段别名
		
		//如果你一定要像下面这句一样不加别名的话就把Person类中的getAddr和setAddr改为getAddress和setAddress,因为QueryRunner的Query方法
		//的类反射是根据数据库字段名来调用getter和setter方法的
		//List<Person> persons=run.query("select id,name,address,age from dbutilsperson", new BeanListHandler<Person>(Person.class));
		System.out.println(persons);
	
	@Test//封装成MapList
	public void query2() throws SQLException
		QueryRunner run=new QueryRunner(C3p0Pool.getDataSource());
		String sql="select * from dbutilsperson";
		List<Map<String, Object>> persons=run.query(sql, new MapListHandler());
		System.out.println(persons);
	
	@Test//封装成BeanList---查询带参数
	public void query3() throws SQLException
		QueryRunner run=new QueryRunner(C3p0Pool.getDataSource());
		String sql="select id,name,address addr,age from dbutilsperson where name like ? and age>?";
		List<Person> persons=run.query(sql, new BeanListHandler<Person>(Person.class), "%a%", 20);//用属性名 当  字段别名
		System.out.println(persons);
	
	
	@Test//演示批处理功能
	public void batch() throws SQLException
		QueryRunner run=new QueryRunner(C3p0Pool.getDataSource());
		for (int i=1;i<=100;i++)
			String sql="insert into dbutilsstud(id,name) values(?,?)";
			String str="000"+i;
			str=str.substring(str.length()-3, str.length());
			String id1="A"+str;
			String id2="B"+str;
			String params[][]=id1,"Jack"+i,id2,"Rose"+i;
			run.batch(sql, params);
		
	
	
	以下演示扩展包commons-dbutilss-ext.jar的功能//
	//注意,下面的用法要生效,必须给值对象添加注解
	@Test//封装成BeanList---直接通过JavaBean的字节码查询
	public void query4()
		ExtQueryRunner run=new ExtQueryRunner(C3p0Pool.getDataSource());
		List<Person> persons=run.query(Person.class);
		System.out.println(persons);
	
	
	@Test//封装成BeanList---直接通过JavaBean的字节码查询
	public void save3()
		ExtQueryRunner run=new ExtQueryRunner(C3p0Pool.getDataSource());
		Stud stud=new Stud();
		stud.setId("A06");
		stud.setName("Jenney");
		run.save(stud);
		System.out.println(stud);
	
上面代码中使用到的两个封装对象用的类如下:

下面两个类加的注解都是为上面代码最后那一部分演示扩展包部分服务的

Person.java

package cn.hncu.dbutils;

import org.apache.commons.dbutils.ext.Table;

@Table(value = "dbutilsperson")
public class Person 
	private String id;
	private String name;
	
	//@Column(value="address")//该注解无效,反正以后开发时属性名都取成和数据库表字段名一样
	//如果你一定要把这里设的和数据库里面的字段名不一样,那么请把这里的getter和setter方法后的名字设置成和数据库字段名一样的,
	//这样照样能设置,因为这个扩展包里面的类反射获取getter和setter方法是根据数据库里面的字段名来设置的,我这里就设置成了和数据         //库字段名一样的,你们可以试试改成和本类的属性名一样的试试,一定无法取到值的
	private String addr;
	
	private int age;
	
	public Person() 
		super();
	

	public String getId() 
		return id;
	

	public void setId(String id) 
		this.id = id;
	

	public String getName() 
		return name;
	

	public void setName(String name) 
		this.name = name;
	

	public int getAge() 
		return age;
	

	public void setAge(int age) 
		this.age = age;
	

	public String getAddress() 
		return addr;
	

	public void setAddress(String addr) 
		this.addr = addr;
	

	@Override
	public int hashCode() 
		final int prime = 31;
		int result = 1;
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		return result;
	

	@Override
	public boolean equals(Object obj) 
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Person other = (Person) obj;
		if (id == null) 
			if (other.id != null)
				return false;
		 else if (!id.equals(other.id))
			return false;
		return true;
	

	@Override
	public String toString() 
		return id + ", " + name + ", " + addr + ", " + age;
	

Stud.java

package cn.hncu.dbutils;

import org.apache.commons.dbutils.ext.Column;
import org.apache.commons.dbutils.ext.Table;

@Table(value="dbutilsstud")
public class Stud 
	@Column
	private String id;
	@Column
	private String name;
	private int age;
	
	public Stud() 
		super();
	

	public String getId() 
		return id;
	

	public void setId(String id) 
		this.id = id;
	

	public String getName() 
		return name;
	

	public void setName(String name) 
		this.name = name;
	

	public int getAge() 
		return age;
	

	public void setAge(int age) 
		this.age = age;
	

	@Override
	public int hashCode() 
		final int prime = 31;
		int result = 1;
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		return result;
	

	@Override
	public boolean equals(Object obj) 
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Stud other = (Stud) obj;
		if (id == null) 
			if (other.id != null)
				return false;
		 else if (!id.equals(other.id))
			return false;
		return true;
	

	@Override
	public String toString() 
		return id + ", " + name + ", "+age;
	



以上是关于数据库连接池工具---DbUtils的主要内容,如果未能解决你的问题,请参考以下文章

数据库连接池工具---DbUtils

Java基础学习笔记二十七 DBUtils和连接池

DBUtils和连接池

DButils工具类和连接池的使用

JDBC连接池&DBUtils

java学习笔记数据库连接池与操作工具类