数据库
首页 > 数据库> > 数据库连接池与DBUtils工具

数据库连接池与DBUtils工具

作者:互联网

一: DBCP数据源
DBCP:是数据库连接池的简称,是Apache组织下的开源连接池的实现,也是Tomcat服务器使用的连接池组件。单独使用DBCP数据源时,需要在应用程序中导入两个JAR包,具体如下:
1.commons-dbcp.jar包
commons-dbcp.jar包是DBCP数据源的实现包,包含所有操作数据库连接信息和数据库连接池初始化信息的方法,并实现了DataSource接口的getConnection()方法。
2. commons-pool.jar包
commons-pool.jar包是DBCP数据库连接池实现包的依赖包,为commons-dbcp.jar包中的方法提供了支持。可以这么说,没有该依赖包,commons-dbcp.jar包中的很多方法就没有办法实现。

二:在chapter13.example下创建一个Example01类:

package chapter13.example;                                                                                                                                                                                                     
                                                                                                                                                                                                                               
import java.awt.image.DataBufferShort;                                                                                                                                                                                         
import java.sql.SQLException;                                                                                                                                                                                                  
                                                                                                                                                                                                                               
import javax.sql.DataSource;                                                                                                                                                                                                   
                                                                                                                                                                                                                               
import org.apache.commons.dbcp.BasicDataSource;                                                                                                                                                                                
                                                                                                                                                                                                                               
import java.sql.DatabaseMetaData;                                                                                                                                                                                              
import java.sql.Connection;                                                                                                                                                                                                    
                                                                                                                                                                                                                               
public class example01 {                                                                                                                                                                                                       
	public static DataSource ds = null;                                                                                                                                                                                        
	static {                                                                                                                                                                                                                   
		BasicDataSource bds = new BasicDataSource();                                                                                                                                                                           
		bds.setDriverClassName("com.mysql.cj.jdbc.Driver");                                                                                                                                                                    
		bds.setUrl( "jdbc:mysql://localhost:3306/jdbc?serverTimezone=UTC");                                                                                                                                                    
		bds.setUsername("root");                                                                                                                                                                                               
		bds.setPassword("123456");                                                                                                                                                                                             
		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());                                                                                                                 
	}                                                                                                                                                                                                                          
}                                                                                                                                                                                                                              

结果
在这里插入图片描述
三:创建一个example02类,该类中采用了从配置文件中获取数据库的连接信息和数据源的初始化信息,具体代码如下:

package chapter13.example;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
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());	
    }
}



创建一个example03类,该类采用C3P0数据源手动代码的方式获取Connection对象.

package chapter13.example;
import java.sql.SQLException;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
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());
	}
}

通过读取配置文件创建数据源对象
使用 ComboPooledDataSource(String configName)构造方法读取c3p0-config.xml配置文件,从而创建数据源对象,然后获取数据库连接对象。在src根目录下创建一个c3p0-config.xml文件,用于设置数据库的连接信息和数据源的初始化信息

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
	<default-config>
		<property name="driverClass">com.mysql.cj.jdbc.Driver</property>
		<property name="jdbcUrl">
     		jdbc:mysql://localhost:3306/jdbc?serverTimezone=UTC
     	</property>
		<property name="user">root</property>
		<property name="password">123456</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="dashuju">
		<property name="driverClass">com.mysql.cj.jdbc.Driver</property>
		<property name="jdbcUrl">
           	jdbc:mysql://localhost:3306/jdbc?serverTimezone=UTC
        </property>
		<property name="user">root</property>
		<property name="password">123456</property>
		<property name="initialPoolSize">5</property>
		<property name="maxPoolSize">15</property>
	</named-config>
</c3p0-config>

创建一个Example04类,该类中使用C3P0数据源从配置文件中获取Connection对象:

package chapter13.example;
 
import java.sql.SQLException;
 
import javax.sql.DataSource;
 
import com.mchange.v2.c3p0.ComboPooledDataSource;
 
public class example04 {
	public static DataSource ds = null;
	static {
		ComboPooledDataSource cpds = new ComboPooledDataSource("dashuju");
		ds = cpds;
	}
	public static void main(String[] args) throws SQLException{
		System.out.println(ds.getConnection());
	}
}

结果
在这里插入图片描述
四: DBUtils工具
1 DBUtils工具介绍
为了更加简单地使用JDBC,Apache组织提供了一个DBUtils工具,它是操作数据库的一个组件,实现了对JDBC的简单封装,可以在不影响性能的情况下极大地简化JDBC的编码工作量。
DBUtils工具核心是org.apache.commons.dbutils.QueryRunner类和org.apache.commons.dbutils.ResultSetHandler接口

2.在名为jdbc的数据库中创建数据表user,创建语句如下。

USE jdbc;
CREATE TABLE user(
id INT(3) PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(20) NOT NULL,
password VARCHAR(20) NOT NULL
);

向user表插入3条数据,具体语句如下

INSERT INTO user (name, password) VALUES ('zhangsan','123456');
INSERT INTO user (name, password) VALUES ('lisi','123456');
INSERT INTO user (name, password) VALUES ('wangwu','123456');

结果
在这里插入图片描述
3创建一个名为BaseDao的类,该类中编写了一个通用的查询方法

package chapter13.example;
 
import java.sql.SQLException;
 
import org.apache.commons.dbutils.ResultSetHandler;
 
 
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Connection;
 
public class basedao {
	//优化查询
	public static Object query(String sql,ResultSetHandler<?> rsh,Object...params) throws SQLException{
		Connection conn = null;
		PreparedStatement pstmt= null; 
		ResultSet rs =null;
		Object obj = null;
		try {
			conn = JDBCUtils.getConnection();
			pstmt = conn.prepareStatement(sql);
			for (int i = 0; params !=null && i<params.length; i++) {
				pstmt.setObject(i+1, params[i]);
			}
			rs = pstmt.executeQuery();
			obj = rsh.handle(rs);
		} catch (Exception e) {
			// TODO: handle exception
			return new Exception(e.getMessage());
		}finally {
			JDBCUtils.release(rs,pstmt,conn);
		}
		return obj;
	}
}

创建实体类User,使用该类来封装User对象

package chapter13.example;
 
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;
	}
}

创建类ResultSetTest1,该类用于演示BeanHandler类对结果集的处理

package chapter13.example;
 
import java.sql.SQLException;
 
import org.apache.commons.dbutils.handlers.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);
		if (object!=null&& object instanceof User) {
			User user = (User) object;
			System.out.println("id为1的User对象的name值为:"+user.getName());
		}else {
			System.out.println("查询结果为空:"+object);
		}
	}
	public static void main(String[] args) throws SQLException{
		testBeanHandler();
	}
}

结果
在这里插入图片描述
创建类ResultSetTest2,该类用于演示BeanListHandler类对结果集的处理

package chapter13.example;
 
import java.sql.SQLException;
import java.util.ArrayList;
 
import org.apache.commons.dbutils.handlers.BeanListHandler;
 
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)+"条数据的userna值为:"+list.get(i).getName());
		}
	}
	public static void main(String[] args) throws SQLException{
		testBeanListHandler();
	}
}

结果
在这里插入图片描述
5.ScalarHandler
创建类 ResultSetTest3,该类用于演示 ScalarHandler类的使用方法

package chapter13.example;
 
import java.sql.SQLException;
 
import org.apache.commons.dbutils.handlers.ScalarHandler;
 
 
public class ResultSetTest03 {
	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();
	}
}

结果
在这里插入图片描述
五:使用DBUtils实现增删改查
创建C3p0Utils类,该类用于创建数据源

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

创建DBUtilsDao类

package chapter13.example;
 
import java.sql.SQLException;
import java.util.List;
 
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
 
public class DBUtilsDao {
	public List findAll() throws SQLException{
		QueryRunner runner = new QueryRunner(C3p0Utils.getDataSource());
		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 runner = new QueryRunner(C3p0Utils.getDataSource());
		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 runner = new QueryRunner(C3p0Utils.getDataSource());
		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 runner = new QueryRunner(C3p0Utils.getDataSource());
		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 runner = new QueryRunner(C3p0Utils.getDataSource());
		String sql = "delete from user where id=?";
		int num = runner.update(sql,id);
		if (num>0) 
			return true;
		return false;
	}
}

测试DBUtilsDao类中的增删改查操作
创建类DBUtilsDaoTest1对增加操作进行测试:

package chapter13.example;
 
import java.sql.SQLException;
 
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();
	}
}

结果
在这里插入图片描述
创建测试类DBUtilsDaoTest2:

package chapter13.example;
 
import java.sql.SQLException;
 
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();
	}
}

结果
在这里插入图片描述

标签:数据库,new,SQLException,user,sql,import,DBUtils,public,连接池
来源: https://blog.csdn.net/qq_55680233/article/details/122276281