数据库连接池

一、dbcp

相应的 包:
mysql-jdbc.jar
commons-dbcp.jar
commons-pool.jar
硬编码使用DBCP(在代码中添加配置)

@Test
	public void test1() throws Exception {
		BasicDataSource source = new BasicDataSource();
		// 设置连接的信息
		source.setDriverClassName("com.mysql.jdbc.Driver");
		source.setUrl("jdbc:mysql://localhost:3306/jdbc-pool");
		source.setUsername("root");
		source.setPassword("123");
		Connection connection = source.getConnection();
		String sql = "select * from student";
		Statement createStatement = connection.createStatement();
		ResultSet executeQuery = createStatement.executeQuery(sql);
		while (executeQuery.next()) {

			System.out.println(executeQuery.getString(2));
		}
		connection.close(); // 回收
	}

软编码使用DBCP(在项目中添加配置文件)

#连接设置
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/day2
username=root
password=111
#<!-- 初始化连接 -->
initialSize=10
#最大连接数量
maxActive=50
#<!-- 最大空闲连接 -->
maxIdle=20
#<!-- 最小空闲连接 -->
minIdle=5
#<!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 -->
maxWait=6000
代码实现
@Test
	public void testSoft() throws Exception {
		BasicDataSourceFactory factory = new BasicDataSourceFactory();
		Properties properties = new Properties();
		// 配置文件添加到properties对象中 javase
		properties.load(new FileInputStream("src/info.properties"));
		// 生成连接池子 需要配置文件
		DataSource source = factory.createDataSource(properties);
		Connection connection = source.getConnection();
		String sql = "select * from student";
		Statement createStatement = connection.createStatement();
		ResultSet executeQuery = createStatement.executeQuery(sql);
		while (executeQuery.next()) {
			System.out.println(executeQuery.getString(2));
		}
		connection.close(); // 回收
	}

二、cp30

需要的包
c3p0-0.9.1.2.jar
mysql-connector-java-5.0.8.jar
配置文件(c3p0-config.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-pool?characterEncoding=utf-8</property>
		<property name="user">root</property>
		<property name="password">123</property>
		<!--扩展配置 -->
		<!-- 连接超过30秒报错 -->
		<property name="checkoutTimeout">30000</property>
		<!--30秒检查空闲连接 -->
		<property name="idleConnectionTestPeriod">30</property>
		<property name="initialPoolSize">10</property>
		<!-- 30秒不适用丢弃 -->
		<property name="maxIdleTime">30</property>
		<property name="maxPoolSize">100</property>
		<property name="minPoolSize">10</property>
	</default-config>
	
	<!-- 命名的配置 -->
	<named-config name="bruce">
		<property name="driverClass">com.mysql.jdbc.Driver</property>
		<property name="jdbcUrl">jdbc:mysql://localhost:3306/day2</property>
		<property name="user">root</property>
		<property name="password">111</property>
		<!-- 如果池中数据连接不够时一次增长多少个 -->
		<property name="acquireIncrement">5</property>
		<property name="initialPoolSize">20</property>
		<property name="minPoolSize">10</property>
		<property name="maxPoolSize">40</property>
	</named-config>
</c3p0-config> 

工具类:

/**
 * 从连接池子中获取连接! C3P0的连接池子 0.获取连接池子对象 DBUtils 1.获取连接 2.关闭资源
 */
public class DataSourceUtils {

	private static ComboPooledDataSource dataSource = new ComboPooledDataSource();

	/**
	 * 返回连接池对象方法
	 * @return c3p0连接池子
	 */
	public static ComboPooledDataSource getDataSource() {
		return dataSource;
	}

	/**
	 * 连接池中获取连接的方法
	 * @return 连接
	 */
	public static Connection getConnection() {

		Connection conn = null;
		try {
			conn = dataSource.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

	// 关闭资源
	public static void close(Connection conn) {
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public static void close(Statement st) {

		if (st != null) {
			try {
				st.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public static void close(ResultSet set) {
		if (set != null) {
			try {
				set.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public static void close(Connection conn, Statement st) {
		close(conn);
		close(st);
	}

	public static void close(Connection conn, Statement st, ResultSet rt) {
		close(conn);
		close(st);
		close(rt);
	}
}

c3p0对数据库进行操作:

	@Test
	public void test1() throws Exception {
		// 1.创建C3P0连接池子
		Connection connection = DataSourceUtils.getConnection();
		Statement createStatement = connection.createStatement();
		String sql = "select * from student;";
		ResultSet resultSet = createStatement.executeQuery(sql);
		while (resultSet.next()) {
			System.out.println(resultSet.getString(1)+"--"+resultSet.getString(2));
		}
		DataSourceUtils.close(connection, createStatement, resultSet);
	}

c3p0与dbcp的区别:

  • dbcp没有自动回收空闲连接的功能
  • c3p0有自动回收空闲连接功能
  • dbcp需要手动设置配置文件(自己写Java代码度配置文件)
  • c3p0不需要手动设置(自动读取配置文件)

三、druid

需要的包:
druid-1.1.10.jar

Druid 是目前比较流行的高性能的,分布式列存储的OLAP框架(具体来说是MOLAP)。它有如下几个特点:

  1. 亚秒级查询

    druid提供了快速的聚合能力以及亚秒级的OLAP查询能力,多租户的设计,是面向用户分析应用的理想方式。

  2. 实时数据注入

    druid支持流数据的注入,并提供了数据的事件驱动,保证在实时和离线环境下事件的实效性和统一性

  3. 可扩展的PB级存储

    druid集群可以很方便的扩容到PB的数据量,每秒百万级别的数据注入。即便在加大数据规模的情况下,也能保证时其效性

  4. 多环境部署

    druid既可以运行在商业的硬件上,也可以运行在云上。它可以从多种数据系统中注入数据,包括hadoop,spark,kafka,storm和samza等

  5. 丰富的社区

    druid拥有丰富的社区,供大家学习

工具类:

public class DruidUtils {

	// 声明连接池对象
	private static DruidDataSource ds;
	static {
		// /实例化数据库连接池对象
		ds = new DruidDataSource();
		// 实例化配置对象
		Properties properties = new Properties();
		try {
			// 加载配置文件内容
			InputStream fis = new FileInputStream("src/db.properties");
			properties.load(fis);
			// 设置驱动类全称
			ds.setDriverClassName(properties.getProperty("driverClassName"));
			// 设置连接的数据库
			ds.setUrl(properties.getProperty("url"));
			// 设置用户名
			ds.setUsername(properties.getProperty("username"));
			// 设置密码
			ds.setPassword(properties.getProperty("password"));
			// 设置最大连接数量
			ds.setMaxActive(Integer.parseInt(properties.getProperty("maxActive")));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// 获取连接对象
	public static Connection getConnection() {
		try {
			return ds.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
}

测试:

public class Druid_Test {

	@Test
	public void test1() {
		List<Student> list = findAll();
		for (Student student : list) {
			System.out.println(student);
		}
		System.out.println("------------");
		
		Student s = find("黎明", "12345");
		System.out.println(s);
	}

	public List<Student> findAll() {
		Connection conn = null;
		PreparedStatement pstat = null;
		ResultSet rs = null;
		List<Student> students = new ArrayList<Student>();
		try {
			conn = DruidUtils.getConnection();
			pstat = conn.prepareStatement("select * from student");
			rs = pstat.executeQuery();
			while (rs.next()) {
				int id = rs.getInt("id");
				String username = rs.getString("username");
				String password = rs.getString("password");
				students.add(new Student(id,username,password));
			}
			return students;
		} catch (Exception e) {
			throw new RuntimeException(e);
		} 
	}

	public Student find(String username, String password) {
		Connection conn = null;
		PreparedStatement pstat = null;
		ResultSet rs = null;
		Student student = null;
		try {
			conn = DruidUtils.getConnection();
			pstat = conn.prepareStatement("select * from student where username=? and password=?");
			pstat.setString(1, username);
			pstat.setString(2, password);
			rs = pstat.executeQuery();
			if (rs.next()) {
				int id = rs.getInt("id");
				student=new Student(id,username,password);
			}
			return student;
		} catch (Exception e) {
			throw new RuntimeException(e);
		} 
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
毕业设计,基于SpringBoot+Vue+MySQL开发的精简博客系统,源码+数据库+毕业论文+视频演示 当下,正处于信息化的时代,许多行业顺应时代的变化,结合使用计算机技术向数字化、信息化建设迈进。以前企业对于博客信息的管理和控制,采用人工登记的方式保存相关数据,这种以人力为主的管理模式已然落后。本人结合使用主流的程序开发技术,设计了一款基于Springboot开发的精简博客系统,可以较大地减少人力、财力的损耗,方便相关人员及时更新和保存信息。本系统主要使用B/S开发模式,在idea开发平台上,运用Java语言设计相关的系统功能模块,MySQL数据库管理相关的系统数据信息,SpringBoot框架设计和开发系统功能架构,最后通过使用Tomcat服务器,在浏览器中发布设计的系统,并且完成系统与数据库的交互工作。本文对系统的需求分析、可行性分析、技术支持、功能设计、数据库设计、功能测试等内容做了较为详细的介绍,并且在本文中也展示了系统主要的功能模块设计界面和操作界面,并对其做出了必要的解释说明,方便用户对系统进行操作和使用,以及后期的相关人员对系统进行更新和维护。本系统的实现可以极大地提高企业的工作效率,提升用户的使用体验,因此在现实生活中运用本系统具有很大的使用价值。 关键词:博客管理;Java语言;B/S结构;MySQL数据库
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值