Home Database Mysql Tutorial MySql数据库连接池_MySQL

MySql数据库连接池_MySQL

Jun 01, 2016 pm 01:02 PM
database

1.传统链接(如下为示意图)

\

注意:

(1).传统方式找DriverManager要连接,数目是有限的。

(2).传统方式的close(),并没有将Connection重用,只是切断应用程序和数据库的桥梁,即无发送到SQL命令到数据库端执行

(3).项目中,对于Connection不说,不会直接使用DriverManager取得,而使用连接池方式。

2.采用连接池(示意图)

\

3.开源数据库连接池

(1).现在很多Web服务器(Weblogic, WebSphere, Tomcat)都提供了DataSoruce的实现,即连接池的实现。通常我们把DataSource的实现,按其英文含义称之为数据源,数据源中都包含了数据库连接池的实现。
(2).也有一些开源组织提供了数据源的独立实现:
DBCP 数据库连接池(tomcat)
C3P0 数据库连接池(hibernate)
(3).实际应用时不需要编写连接数据库代码,直接从数据源获得数据库的连接。程序员编程时也应尽量使用这些数据源的实现,以提升程序的数据库访问性能。

4.C3P0的使用:
(1).在classpath的路径下配置xml文件,即src的文件下而且这个文件名必须是c3p0-config.xml

原始的c3p0-config.xml的文件参数:

<c3p0-config>
	<default-config>
		<!-- 当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
		<property name="acquireIncrement">3</property>

		<!-- 定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 -->
		<property name="acquireRetryAttempts">30</property>

		<!-- 两次连接中间隔时间,单位毫秒。Default: 1000 -->
		<property name="acquireRetryDelay">1000</property>

		<!-- 连接关闭时默认将所有未提交的操作回滚。Default: false -->
		<property name="autoCommitOnClose">false</property>

		<!--
			c3p0将建一张名为Test的空表,并使用其自带的查询语句进行测试。如果定义了这个参数那么
			属性preferredTestQuery将被忽略。你不能在这张Test表上进行任何操作,它将只供c3p0测试 使用。Default:
			null
		-->
		<property name="automaticTestTable">Test</property>

		<!--
			获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效
			保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试
			获取连接失败后该数据源将申明已断开并永久关闭。Default: false
		-->
		<property name="breakAfterAcquireFailure">false</property>

		<!--
			当连接池用完时客户端调用getConnection()后等待获取新连接的时间,超时后将抛出
			SQLException,如设为0则无限期等待。单位毫秒。Default: 0
		-->
		<property name="checkoutTimeout">100</property>

		<!--
			通过实现ConnectionTester或QueryConnectionTester的类来测试连接。类名需制定全路径。 Default:
			com.mchange.v2.c3p0.impl.DefaultConnectionTester
		-->
		<property name="connectionTesterClassName"></property>

		<!--
			指定c3p0 libraries的路径,如果(通常都是这样)在本地即可获得那么无需设置,默认null即可 Default: null
		-->
		<property name="factoryClassLocation">null</property>

		<!--
			Strongly disrecommended. Setting this to true may lead to subtle and
			bizarre bugs. (文档原文)作者强烈建议不使用的一个属性
		-->
		<property name="forceIgnoreUnresolvedTransactions">false</property>

		<!-- 每60秒检查所有连接池中的空闲连接。Default: 0 -->
		<property name="idleConnectionTestPeriod">60</property>

		<!-- 初始化时获取三个连接,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
		<property name="initialPoolSize">3</property>

		<!-- 最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
		<property name="maxIdleTime">60</property>

		<!-- 连接池中保留的最大连接数。Default: 15 -->
		<property name="maxPoolSize">15</property>

		<!--
			JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements
			属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。
			如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0
		-->
		<property name="maxStatements">100</property>

		<!--
			maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数。Default: 0
		-->
		<property name="maxStatementsPerConnection"></property>

		<!--
			c3p0是异步操作的,缓慢的JDBC操作通过帮助进程完成。扩展这些操作可以有效的提升性能
			通过多线程实现多个操作同时被执行。Default: 3
		-->
		<property name="numHelperThreads">3</property>

		<!--
			当用户调用getConnection()时使root用户成为去获取连接的用户。主要用于连接池连接非c3p0 的数据源时。Default:
			null
		-->
		<property name="overrideDefaultUser">root</property>

		<!-- 与overrideDefaultUser参数对应使用的一个参数。Default: null-->
		<property name="overrideDefaultPassword">password</property>

		<!-- 密码。Default: null-->
		<property name="password"></property>

		<!--
			定义所有连接测试都执行的测试语句。在使用连接测试的情况下这个一显著提高测试速度。注意:
			测试的表必须在初始数据源的时候就存在。Default: null
		-->
		<property name="preferredTestQuery">select id from test where id=1
		</property>

		<!-- 用户修改系统配置参数执行前最多等待300秒。Default: 300 -->
		<property name="propertyCycle">300</property>

		<!--
			因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection提交的
			时候都将校验其有效性。建议使用idleConnectionTestPeriod或automaticTestTable
			等方法来提升连接测试的性能。Default: false
		-->
		<property name="testConnectionOnCheckout">false</property>

		<!-- 如果设为true那么在取得连接的同时将校验连接的有效性。Default: false -->
		<property name="testConnectionOnCheckin">true</property>

		<!-- 用户名。Default: null-->
		<property name="user">root</property>

		<!--
			早期的c3p0版本对JDBC接口采用动态反射代理。在早期版本用途广泛的情况下这个参数允许用户恢复到动态反射代理以解决不稳定的故障。最新的非反射代理更快并且已经开始广泛的被使用,所以这个参数未必有用。现在原先的动态反射与新的非反射代理同时受到支持,但今后可能的版本可能不支持动态反射代理。Default:
			false。
		-->
		<property name="usesTraditionalReflectiveProxies">false</property>
		<property name="automaticTestTable">con_test</property>
		<property name="checkoutTimeout">30000</property>
		<property name="idleConnectionTestPeriod">30</property>
		<property name="initialPoolSize">10</property>
		<property name="maxIdleTime">30</property>
		<property name="maxPoolSize">25</property>
		<property name="minPoolSize">10</property>
		<property name="maxStatements">0</property>
		<user-overrides user="swaldman">
		</user-overrides>
	</default-config>
	<named-config name="dumbTestConfig">
		<property name="maxStatements">200</property>
		<user-overrides user="poop">
			<property name="maxStatements">300</property>
		</user-overrides>
	</named-config>
</c3p0-config>
Copy after login
实战练习:
1>.首先配置c3p0-config.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
	<default-config>
		<property name="driverClass">com.mysql.jdbc.Driver</property>
		<property name="user">root</property>
		<property name="password">wwh</property>
		<property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/jdbctest</property>
	</default-config>
</c3p0-config>
Copy after login
2>.代码操作连接(TestC3P0.java)
package cn.wwh.www.java.jdbc.datasource;

import java.sql.Connection;

import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
 *类的作用:
 *
 *
 *@author 一叶扁舟
 *@version 1.0
 *@创建时间: 2014-9-2   上午12:02:13
 */

//测试连接池C3P0的用法
public class TestC3P0 {
	public static void main(String[] args) throws Exception {
		long begin = System.currentTimeMillis();
		//创建C3P0连接池,并加载c3p0-config.xml文件
		ComboPooledDataSource dataSource = new ComboPooledDataSource();
		for(int i=1;i<=1000000;i++){
			Connection conn = dataSource.getConnection();
			if(conn!=null){
				System.out.println("获取连接第"+i+"个");
				conn.close();
			}
		}
		long end = System.currentTimeMillis();
		System.out.println("用了" + (end-begin)/1000+"秒");
	}
}
Copy after login

5.DBCP的使用:
(1).采用类加载的方式,文件名是:dbcp.properties

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/jdbctest
username=root
password=wwh
Copy after login
(2).在代码中使用(TestDBCP.java)
package cn.wwh.www.java.jdbc.datasource;

import java.io.InputStream;
import java.sql.Connection;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSourceFactory;

/**
 *类的作用:采用DBCP连接池的方式去获取数据库的链接,并测试他的时间
 *
 *
 *@author 一叶扁舟
 *@version 1.0
 *@创建时间: 2014-9-1   下午09:27:59
 */

//测试连接池DBCP的用法
public class TestDBCP {
	public static void main(String[] args) throws Exception {
		long begin = System.currentTimeMillis();
		//加载属性文件
		InputStream is = TestDBCP.class.getClassLoader().getResourceAsStream("cn/wwh/www/java/jdbc/config/dbcp.properties");
		Properties props = new Properties();
		props.load(is);
		//创建DBCP连接池工厂
		BasicDataSourceFactory factory = new BasicDataSourceFactory(); 
		//创建数据源,即连接池
		DataSource ds = factory.createDataSource(props);
		for(int i=1;i<=1000000;i++){
			//从连接池中取得一个空闲的连接对象
			Connection conn = ds.getConnection();
			if(conn!=null){
				System.out.println("获取连接第"+i+"个");
			}
			//将连接对象还回给连接池
			conn.close();
		}
		long end = System.currentTimeMillis();
		System.out.println("用了" + (end-begin)/1000+"秒");
	}
}
Copy after login
第一的测试时间为18秒,第二个的测试时间为13秒,不同的机器性能不一样,测试的时间快慢也不可能。但是理论上C3P0的速度应该更快,但是我测试的数据却恰恰相反,很是奇怪。

总结:

1>DBCP和C3P0,都是Java开源的,都必须直接或间接实现javax.sql.DataSource接口
2>DBCP连接池需要dbcp.properties文件,同时需加入3个对应的jar包
3>C3P0连接池需要在/WEB-INF/classes/目录下存放c3p0-config.xml文件,该类ComboPooledDataSource在创建时
会自动在指定的目录下找xml文件,并加载默认设置

4>tomcat用的也是c3p0

6.导入的jar包

commons-dbcp.jar:DBCP实现要导入的jar

commons-pool.jar: 连接池实现的依赖类

commons-collections.jar :连接池实现的集合类

c3p0-0.9.1.2.jar :C3P0实现要导入的jar包

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1665
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos Jul 18, 2024 am 05:48 AM

Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

How does Hibernate implement polymorphic mapping? How does Hibernate implement polymorphic mapping? Apr 17, 2024 pm 12:09 PM

Hibernate polymorphic mapping can map inherited classes to the database and provides the following mapping types: joined-subclass: Create a separate table for the subclass, including all columns of the parent class. table-per-class: Create a separate table for subclasses, containing only subclass-specific columns. union-subclass: similar to joined-subclass, but the parent class table unions all subclass columns.

How to handle database connection errors in PHP How to handle database connection errors in PHP Jun 05, 2024 pm 02:16 PM

To handle database connection errors in PHP, you can use the following steps: Use mysqli_connect_errno() to obtain the error code. Use mysqli_connect_error() to get the error message. By capturing and logging these error messages, database connection issues can be easily identified and resolved, ensuring the smooth running of your application.

Detailed tutorial on establishing a database connection using MySQLi in PHP Detailed tutorial on establishing a database connection using MySQLi in PHP Jun 04, 2024 pm 01:42 PM

How to use MySQLi to establish a database connection in PHP: Include MySQLi extension (require_once) Create connection function (functionconnect_to_db) Call connection function ($conn=connect_to_db()) Execute query ($result=$conn->query()) Close connection ( $conn->close())

How to use database callback functions in Golang? How to use database callback functions in Golang? Jun 03, 2024 pm 02:20 PM

Using the database callback function in Golang can achieve: executing custom code after the specified database operation is completed. Add custom behavior through separate functions without writing additional code. Callback functions are available for insert, update, delete, and query operations. You must use the sql.Exec, sql.QueryRow, or sql.Query function to use the callback function.

How to save JSON data to database in Golang? How to save JSON data to database in Golang? Jun 06, 2024 am 11:24 AM

JSON data can be saved into a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods to parse JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.

PHP connections to different databases: MySQL, PostgreSQL, Oracle and more PHP connections to different databases: MySQL, PostgreSQL, Oracle and more Jun 01, 2024 pm 03:02 PM

PHP database connection guide: MySQL: Install the MySQLi extension and create a connection (servername, username, password, dbname). PostgreSQL: Install the PgSQL extension and create a connection (host, dbname, user, password). Oracle: Install the OracleOCI8 extension and create a connection (servername, username, password). Practical case: Obtain MySQL data, PostgreSQL query, OracleOCI8 update record.

How to handle database connections and operations using C++? How to handle database connections and operations using C++? Jun 01, 2024 pm 07:24 PM

Use the DataAccessObjects (DAO) library in C++ to connect and operate the database, including establishing database connections, executing SQL queries, inserting new records and updating existing records. The specific steps are: 1. Include necessary library statements; 2. Open the database file; 3. Create a Recordset object to execute SQL queries or manipulate data; 4. Traverse the results or update records according to specific needs.

See all articles