搜尋
首頁資料庫mysql教程c3p0开源数据库连接池(DataSource)

c3p0开源数据库连接池(DataSource)

Jun 07, 2016 pm 04:01 PM
datasource開源資料庫現在連接

现在很多WEB服务器(Weblogic, WebSphere, Tomcat)都提供了DataSoruce的实现,即连接池的实现。通常我们把DataSource的实现,按其英文含义称之为数据源,数据源中都包含了数据库连接池的实现。 也有一些开源组织提供了数据源的独立实现: ①DBCP 数据库连接池

现在很多WEB服务器(Weblogic, WebSphere, Tomcat)都提供了DataSoruce的实现,即连接池的实现。通常我们把DataSource的实现,按其英文含义称之为数据源,数据源中都包含了数据库连接池的实现。
也有一些开源组织提供了数据源的独立实现:
①DBCP 数据库连接池
②C3P0 数据库连接池(使用最简单方便)
③Apache Tomcat内置的连接池(apache dbcp)

实际应用时不需要编写连接数据库代码,直接从数据源获得数据库的连接。程序员编程时也应尽量使用这些数据源的实现,以提升程序的数据库访问性能。

使用时,需要新建java工程,在工程中建立“lib”目录,其中添加c3p0-0.9.1.2.jar和mysql-connector-java-5.0.8-bin.jar(mysql驱动)包,并add to build path。

第一种方法:不使用xml配置文件。

/**
 * 演示c3p0的使用方法
 * @project_name Day11   
 * @class_name C3P0Demo   
 * @author Dovinya
 * @data 2014-8-27 下午07:57:42   
 * @version 1
 * @notes
 */
public class C3P0Demo {
	
	@Test
	public void operateDatabase() {
		Connection conn =null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
//			Class.forName("com.mysql.jdbc.Driver");
//			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/day11", "root", "123");
//			ps = conn.prepareStatement("select * from account");
			ComboPooledDataSource dataSource = new ComboPooledDataSource();
			
			
			dataSource.setDriverClass("com.mysql.jdbc.Driver");
			dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/day11");
			dataSource.setUser("root");
			dataSource.setPassword("123");
			
			
			conn = dataSource.getConnection();
			ps = conn.prepareStatement("select * from account");
			rs = ps.executeQuery();
			
			while(rs.next()){
				String name = rs.getString("name");
				System.out.println(name);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(rs!=null){
				try {
					rs.close();
				} catch (SQLException e) {
					
					e.printStackTrace();
				}finally{
					rs=null;
				}
			}
			
			if(ps!=null){
				try {
					ps.close();
				} catch (SQLException e) {
					
					e.printStackTrace();
				}finally{
					ps=null;
				}
			}
			
			if(conn!=null){
				try {
					conn.close();
				} catch (SQLException e) {
					
					e.printStackTrace();
				}finally{
					conn=null;
				}
			}			
		
		}
	}
	
}
第二种方法:使用xml配置文件,这种方法更常见和普遍。

先新建xml文件,命名为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:///day11</property>
		<property name="user">root</property>
		<property name="password">123</property>

		<property name="acquireIncrement">3</property>  <!--当连接池中已经没有连接时,连接池自动获取连接时一次获取的连接个数-->
		<property name="initialPoolSize">10</property>  <!--初始化连接池时,获取的连接个数-->
		<property name="minPoolSize">2</property>       <!--连接池应该保有的最小连接的数量--> 
		<property name="maxPoolSize">10</property>      <!--连接池中可以保有的最大连接数量-->
	</default-config>
</c3p0-config>
然后,新建java文件,在其中添加如下代码:
import com.mchange.v2.c3p0.ComboPooledDataSource;
/**
 * 演示c3p0的使用方法
 * @project_name Day11   
 * @class_name C3P0Demo   
 * @author Dovinya
 * @data 2014-8-27 下午07:57:42   
 * @version 1
 * @notes
 */
public class C3P0Demo {
	
	@Test
	public void operateDatabase() {
		Connection conn =null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {

			ComboPooledDataSource dataSource = new ComboPooledDataSource();
			
			conn = dataSource.getConnection();
			ps = conn.prepareStatement("select * from account");
			rs = ps.executeQuery();
			
			while(rs.next()){
				String name = rs.getString("name");
				System.out.println(name);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(rs!=null){
				try {
					rs.close();
				} catch (SQLException e) {
					
					e.printStackTrace();
				}finally{
					rs=null;
				}
			}
			
			if(ps!=null){
				try {
					ps.close();
				} catch (SQLException e) {
					
					e.printStackTrace();
				}finally{
					ps=null;
				}
			}
			
			if(conn!=null){
				try {
					conn.close();
				} catch (SQLException e) {
					
					e.printStackTrace();
				}finally{
					conn=null;
				}
			}			
		
		}
	}
	
}
开发时常用。
陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
在MySQL中使用視圖的局限性是什麼?在MySQL中使用視圖的局限性是什麼?May 14, 2025 am 12:10 AM

mysqlviewshavelimitations:1)他們不使用Supportallsqloperations,限制DatamanipulationThroughViewSwithJoinsOrsubqueries.2)他們canimpactperformance,尤其是withcomplexcomplexclexeriesorlargedatasets.3)

確保您的MySQL數據庫:添加用戶並授予特權確保您的MySQL數據庫:添加用戶並授予特權May 14, 2025 am 12:09 AM

porthusermanagementinmysqliscialforenhancingsEcurityAndsingsmenting效率databaseoperation.1)usecReateusertoAddusers,指定connectionsourcewith@'localhost'or@'%'。

哪些因素會影響我可以在MySQL中使用的觸發器數量?哪些因素會影響我可以在MySQL中使用的觸發器數量?May 14, 2025 am 12:08 AM

mysqldoes notimposeahardlimitontriggers,butacticalfactorsdeterminetheireffactective:1)serverConfiguration impactactStriggerGermanagement; 2)複雜的TriggerSincreaseSySystemsystem load; 3)largertablesslowtriggerperfermance; 4)highConconcConcrencerCancancancancanceTigrignecentign; 5); 5)

mysql:存儲斑點安全嗎?mysql:存儲斑點安全嗎?May 14, 2025 am 12:07 AM

Yes,it'ssafetostoreBLOBdatainMySQL,butconsiderthesefactors:1)StorageSpace:BLOBscanconsumesignificantspace,potentiallyincreasingcostsandslowingperformance.2)Performance:LargerrowsizesduetoBLOBsmayslowdownqueries.3)BackupandRecovery:Theseprocessescanbe

mySQL:通過PHP Web界面添加用戶mySQL:通過PHP Web界面添加用戶May 14, 2025 am 12:04 AM

通過PHP網頁界面添加MySQL用戶可以使用MySQLi擴展。步驟如下:1.連接MySQL數據庫,使用MySQLi擴展。 2.創建用戶,使用CREATEUSER語句,並使用PASSWORD()函數加密密碼。 3.防止SQL注入,使用mysqli_real_escape_string()函數處理用戶輸入。 4.為新用戶分配權限,使用GRANT語句。

mysql:blob和其他無-SQL存儲,有什麼區別?mysql:blob和其他無-SQL存儲,有什麼區別?May 13, 2025 am 12:14 AM

mysql'sblobissuitableForStoringBinaryDataWithInareLationalDatabase,而ilenosqloptionslikemongodb,redis和calablesolutionsolutionsolutionsoluntionsoluntionsolundortionsolunsonstructureddata.blobobobissimplobisslowdeperformberbutslowderformandperformancewithlararengedata;

mySQL添加用戶:語法,選項和安全性最佳實踐mySQL添加用戶:語法,選項和安全性最佳實踐May 13, 2025 am 12:12 AM

toaddauserinmysql,使用:createUser'username'@'host'Indessify'password'; there'showtodoitsecurely:1)choosethehostcarecarefullytocon trolaccess.2)setResourcelimitswithoptionslikemax_queries_per_hour.3)usestrong,iniquepasswords.4)Enforcessl/tlsconnectionswith

MySQL:如何避免字符串數據類型常見錯誤?MySQL:如何避免字符串數據類型常見錯誤?May 13, 2025 am 12:09 AM

toAvoidCommonMistakeswithStringDatatatPesInMysQl,CloseStringTypenuances,chosethirtightType,andManageEngencodingAndCollat​​ionsEttingSefectery.1)usecharforfixed lengengtrings,varchar forvariable-varchar forbariaible length,andtext/blobforlargerdataa.2 seterters seterters seterters

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。