数据库连接池与DBUtils工具

本文介绍了数据库连接池的概念,包括Apache的DBCP和C3P0数据源的使用方式,强调了DataSource接口在建立数据库连接中的作用。此外,详细讲解了DBUtils工具的运用,包括QueryRunner、ResultSetHandler接口及其实现类的功能,并展示了如何进行增删改查操作。
摘要由CSDN通过智能技术生成

1. 什么是数据库连接池
数据库连接池在初始化时将创建一定数量的的数据库连接池放在连接池中,当应用程序访问数据库是病不是直接创建Connection,而是向连接池申请一个Connection。如果连接池中有空闲的Connection,则将其返回,否则创建新的Connection。
DataSource接口
为了获取数据库连接对象(Connection),JDBC提供了java.sql.DataSource接口,它负责与数据库建立连接,并定义返回值为Connection对象方法,具体如下:

  • Connection getConnection()–通过无参的方法建立数据库的连接
  • Connection getConnection(String username,String password)–通过传入登录信息的方式建立与数据库的连接

DBCP数据库
是数据库连接池(DataBase Connection Pool)的简称,是Apache组织下的开源连接池实现也是Tomcat服务器使用的连接池组件。单独使用DBCP数据源时,需要在应用程序中导入两个JAR包

  • commons-dbcp.jar包
  • commons-pool.jar包
    1、通过BasicDataSource类直接创建数据源对象
    在eclipse中创建一个web项目,导入所需要的的jar包,在src目录下创建一个包在创建一个Example01类
public class Example01 {
	public static DataSource ds = null;
	static {
		// 获取DBCP数据源实现类对象
		BasicDataSource bds = new BasicDataSource();
		// 设置连接数据库需要的配置信息
		bds.setDriverClassName("com.mysql.jdbc.Driver");
		bds.setUrl("jdbc:mysql://localhost:3306/jdbc");
		bds.setUsername("root");
		bds.setPassword("itcast");
		// 设置连接池的参数
		bds.setInitialSize(5);
		bds.setMaxActive(5);
		ds = bds;
	}
	public static void main(String[] args) throws SQLException {
		// 获取数据库连接对象
		Connection conn = ds.getConnection();
		//获取数据库连接信息
		DatabaseMetaData metaData = conn.getMetaData();
		//打印数据库连接信息
		System.out.println(metaData.getURL()
             +",UserName="+metaData.getUserName()
             +","+metaData.getDriverName());
	}
}

2、通过读取数据配置文件创建数据源对象

public class Example02 {
	public static DataSource ds = null;
	static {
		// 新建一个配置文件对象
		Properties prop = new Properties();
		try {
			// 通过类加载器找到文件路径,读配置文件
			InputStream in = new Example02().getClass().getClassLoader()
					.getResourceAsStream("dbcpconfig.properties");
			// 把文件以输入流的形式加载到配置对象中
			prop.load(in);
			// 创建数据源对象
			ds = BasicDataSourceFactory.createDataSource(prop);
		} catch (Exception e) {
			throw new ExceptionInInitializerError(e);
		}
	}
	public static void main(String[] args) throws SQLException {
		// 获取数据库连接对象
		Connection conn = ds.getConnection();
		//获取数据库连接信息
		DatabaseMetaData metaData = conn.getMetaData();
		//打印数据库连接信息
         System.out.println(metaData.getURL()
              +",UserName="+metaData.getUserName()   
                    +","+metaData.getDriverName());	
    }
}

3、C3P0数据源
C3P0数据源是目前最流行的开源数据库连接池之一,它实现了DataSource数据源接口,支持JDBC2和JDBC3的标准规范,易于扩展并且性能优越,著名的开源框架Hibernate和Spring都支持该数据。
当使用C3P0数据源时,首先需要构建数据源对象,创建数据源对象可以使用Combo-PooledDataSource类。

(1)通过Combo-PooledDataSource()构造方法创建数据源对象

public class Example03 {
	public static DataSource ds = null;
	// 初始化C3P0数据源
	static {
		ComboPooledDataSource cpds = new ComboPooledDataSource();
		// 设置连接数据库需要的配置信息
		try {
			cpds.setDriverClass("com.mysql.jdbc.Driver");
			cpds.setJdbcUrl("jdbc:mysql://localhost:3306/jdbc");
			cpds.setUser("root");
			cpds.setPassword("itcast");
			// 设置连接池的参数
			cpds.setInitialPoolSize(5);
			cpds.setMaxPoolSize(15);
			ds = cpds;
		} catch (Exception e) {
			throw new ExceptionInInitializerError(e);
		}
	}
	public static void main(String[] args) throws SQLException {
		// 获取数据库连接对象
		System.out.println(ds.getConnection());
	}
}

(2)通过读取配置文件创建数据源对象

  • 在src根目录下创建一个xml文件,用于设置数据库的连接信息和数据源的初始化信息。
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
	<default-config>
		<property name="driverClass">com.mysql.jdbc.Driver</property>
		<property name="jdbcUrl">
     		jdbc:mysql://localhost:3306/jdbc
     	</property>
		<property name="user">root</property>
		<property name="password">root</property>
		<property name="checkoutTimeout">30000</property>
		<property name="initialPoolSize">10</property>
		<property name="maxIdleTime">30</property>
		<property name="maxPoolSize">100</property>
		<property name="minPoolSize">10</property>
		<property name="maxStatements">200</property>
	</default-config> 
	<named-config name="itcast">
		<property name="driverClass">com.mysql.jdbc.Driver</property>
		<property name="jdbcUrl">
           	jdbc:mysql://localhost:3306/jdbc
        </property>
		<property name="user">root</property>
		<property name="password">itcast</property>
		<property name="initialPoolSize">5</property>
		<property name="maxPoolSize">15</property>
	</named-config>
</c3p0-config>

  • 创建一个Example04类,用于使用C0P0数据数据源中配置文件中获取Connection对象
 public class Example04 {
 	public static DataSource ds = null;
 	// 初始化C3P0数据源
 	static {
 		// 使用c3p0-config.xml配置文件中的named-config节点中name属性的值
 		ComboPooledDataSource cpds = new ComboPooledDataSource("itcast");
 		ds = cpds;
 	}
 	public static void main(String[] args) throws SQLException {
 		System.out.println(ds.getConnection());
 	}
 }

二、DBUtils工具

DbUtils 是一个jdbc的工具,使用的范围内非常广,主要是为了简化jdbc的代码。
核心类:QueryRunner; ResultSetHandler(是一个接口,主要是完成ORM映射,把结果街转化成我们需要的java对象)
三个核心功能类:

QueryRunner中提供对sql语句操作的API—update和query

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

DbUtils类,它就是一个工具类,定义了关闭资源与事务处理的方法
1、ResultSetHandler实现类

public class DBUtilsDao {
	// 查询所有,返回List集合
	public List findAll() throws SQLException {
		// 创建QueryRunner对象
		QueryRunner runner = new QueryRunner(C3p0Utils.getDataSource());
		// 写SQL语句
		String sql = "select * from user";
		// 调用方法
		List list = (List) runner.query(sql,
                     new BeanListHandler(User.class));
		return list;
	}
	// 查询单个,返回对象
	public User find(int id) throws SQLException {
		// 创建QueryRunner对象
		QueryRunner runner = new QueryRunner(C3p0Utils.getDataSource());
		// 写SQL语句
		String sql = "select * from user where id=?";
		// 调用方法
		User user = (User) runner.query(sql, 
                 new BeanHandler(User.class), new Object[] { id });
		return user;
	}
	// 添加用户的操作
	public Boolean insert(User user) throws SQLException {
		// 创建QueryRunner对象
		QueryRunner runner = new QueryRunner(C3p0Utils.getDataSource());
		// 写SQL语句
		String sql = "insert into user (name,password) values (?,?)";
		// 调用方法
		int num = runner.update(sql,
				new Object[] { user.getName(), user.getPassword() });
		if (num > 0)
			return true;
		return false;
	}
	// 修改用户的操作
	public Boolean update(User user) throws SQLException {
		// 创建QueryRunner对象
		QueryRunner runner = new QueryRunner(C3p0Utils.getDataSource());
		// 写SQL语句
		String sql = "update  user set name=?,password=? where id=?";
		// 调用方法
		int num = runner.update(sql, new Object[] { user.getName(),
                     user.getPassword(),user.getId() });
		if (num > 0)
			return true;
		return false;
	}
	// 删除用户的操作
	public Boolean delete(int id) throws SQLException {
		// 创建QueryRunner对象
		QueryRunner runner = new QueryRunner(C3p0Utils.getDataSource());
		// 写SQL语句
		String sql = "delete from user where id=?";
		// 调用方法
		int num = runner.update(sql, id);
		if (num > 0)
			return true;
		return false;
	}
}

(2)创建一个实体类user,用来封装user对象

public class User {
	private int id;
	private String name;
	private String password;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
}

(3)在创建一个ResultSetTest1,该类用于演示beanHandler类对结果集的处理

public class ResultSetTest1 {
	public static void testBeanHandler() throws SQLException {
		BaseDao basedao = new BaseDao();
		String sql = "select * from user where id=?";
		// 获取查询结果
		Object object = basedao.query(sql, new BeanHandler(User.class), 1);
		// 判断查询结果,如果是User类就进行打印,否则打印查询的结果信息
		if (object!=null && object instanceof User){
			User user= (User) object;
			System.out.print("id为1的User对象的name值为:" + user.getName());
		}else {
			System.out.println("查询结果为空: "+object);
		}
	}
	public static void main(String[] args) throws SQLException {
		testBeanHandler();
	}
}

(4)在创建一个ResultSetTest2,该类用于演示BeanHandler类对结果集的处理

public class ResultSetTest2 {
	public static void testBeanListHandler() throws SQLException {
		BaseDao basedao = new BaseDao();
		String sql = "select * from user ";
		ArrayList<User> list = (ArrayList<User>) basedao.query(sql,
				new BeanListHandler(User.class));
		for (int i = 0; i < list.size(); i++) {
			System.out.println("第" + (i + 1) + "条数据的username值为:"
					+ list.get(i).getName());
		}
	}
	public static void main(String[] args) throws SQLException {
		testBeanListHandler();
	}
}

2、ScalarHandler

本方法是用于处理单行单列的数据,多用于聚合函数的查询,但是以一个点需要注意,就是当聚合函数是涉及到 数字类型的时候,一定要注意返回值类型的转换.
(1)在创建一个ResultSetTest3,该类用于演示BeanHandler类对结果集的处理。

public class ResultSetTest3 {
public static void testScalarHandler() throws SQLException {
	BaseDao basedao = new BaseDao();
	String sql = "select * from user where id=?";
	Object arr = (Object) basedao.query(sql, 
                           new ScalarHandler("name"), 1);
		System.out.println(arr);
	}
	public static void main(String[] args) throws SQLException {
		testScalarHandler();
	}
}

增删改查
1、创建C3p0Utils类
该类用于创建数据库

import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class C3p0Utils {
	private static DataSource ds;
	static {
		ds = new ComboPooledDataSource();
	}
	public static DataSource getDataSource() {
		return ds;
	}
}

2、创建一个DBUtilsDao类,该类实现了对user表的增删改查的基本操作。

public class DBUtilsDao {
	// 查询所有,返回List集合
	public List findAll() throws SQLException {
		// 创建QueryRunner对象
		QueryRunner runner = new QueryRunner(C3p0Utils.getDataSource());
		// 写SQL语句
		String sql = "select * from user";
		// 调用方法
		List list = (List) runner.query(sql,
                     new BeanListHandler(User.class));
		return list;
	}
	// 查询单个,返回对象
	public User find(int id) throws SQLException {
		// 创建QueryRunner对象
		QueryRunner runner = new QueryRunner(C3p0Utils.getDataSource());
		// 写SQL语句
		String sql = "select * from user where id=?";
		// 调用方法
		User user = (User) runner.query(sql, 
                 new BeanHandler(User.class), new Object[] { id });
		return user;
	}
	// 添加用户的操作
	public Boolean insert(User user) throws SQLException {
		// 创建QueryRunner对象
		QueryRunner runner = new QueryRunner(C3p0Utils.getDataSource());
		// 写SQL语句
		String sql = "insert into user (name,password) values (?,?)";
		// 调用方法
		int num = runner.update(sql,
				new Object[] { user.getName(), user.getPassword() });
		if (num > 0)
			return true;
		return false;
	}
	// 修改用户的操作
	public Boolean update(User user) throws SQLException {
		// 创建QueryRunner对象
		QueryRunner runner = new QueryRunner(C3p0Utils.getDataSource());
		// 写SQL语句
		String sql = "update  user set name=?,password=? where id=?";
		// 调用方法
		int num = runner.update(sql, new Object[] { user.getName(),
                     user.getPassword(),user.getId() });
		if (num > 0)
			return true;
		return false;
	}
	// 删除用户的操作
	public Boolean delete(int id) throws SQLException {
		// 创建QueryRunner对象
		QueryRunner runner = new QueryRunner(C3p0Utils.getDataSource());
		// 写SQL语句
		String sql = "delete from user where id=?";
		// 调用方法
		int num = runner.update(sql, id);
		if (num > 0)
			return true;
		return false;
	}
}

3、测试DBUtilsDao类中的增删改查操作

public class DBUtilsDaoTest1 {
	private static DBUtilsDao dao = new DBUtilsDao();
	public static void testInsert() throws SQLException {
		User user = new User();
		user.setName("zhaoliu");
		user.setPassword("666666");
		boolean b = dao.insert(user);
		System.out.println(b);
	}
	public static void main(String[] args) throws SQLException {
		testInsert();
	}
}

(2)修改数据

public class DBUtilsDaoTest2 {
	private static DBUtilsDao dao = new DBUtilsDao();
	public static void testupdate() throws SQLException {
		User user = new User();
		user.setName("zhaoliu");
		user.setPassword("666777");
		user.setId(4);
		boolean b = dao.update(user);
		System.out.println(b);
	}
	public static void main(String[] args) throws SQLException {
		testupdate();
	}
}

(3)删除数据

public class DBUtilsDaoTest3 {
	private static DBUtilsDao dao = new DBUtilsDao();
	public static void testdelete() throws SQLException {
		boolean b = dao.delete(4);
		System.out.println(b);
	}
	public static void main(String[] args) throws SQLException {
		testdelete();
	}
}

(4)查询数据

public class DBUtilsDaoTest4 {
	private static DBUtilsDao dao = new DBUtilsDao();
	public static void testfind() throws SQLException {
		User user = dao.find(2);
		System.out.println(user.getId() + "," + user.getName() + ","
				+ user.getPassword());
	}
	public static void main(String[] args) throws SQLException {
		testfind();
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值