什么是數(shù)據(jù)庫(kù)連接池
有這樣的一種現(xiàn)象:
用java代碼操作數(shù)據(jù)庫(kù),需要數(shù)據(jù)庫(kù)連接對(duì)象,一個(gè)用戶(hù)至少要用到一個(gè)連接?,F(xiàn)在假設(shè)有成千上百萬(wàn)個(gè)用戶(hù),就要?jiǎng)?chuàng)建十分巨大數(shù)量的連接對(duì)象,這會(huì)使數(shù)據(jù)庫(kù)承受極大的壓力,為了解決這種現(xiàn)象,一種技術(shù)出現(xiàn)了,這就是數(shù)據(jù)庫(kù)連接池。
數(shù)據(jù)庫(kù)連接池的原理
所謂數(shù)據(jù)庫(kù)連接池,可以看作 :在用戶(hù)和數(shù)據(jù)庫(kù)之間創(chuàng)建一個(gè)”池”,這個(gè)池中有若干個(gè)連接對(duì)象,當(dāng)用戶(hù)想要連接數(shù)據(jù)庫(kù),就要先從連接池中獲取連接對(duì)象,然后操作數(shù)據(jù)庫(kù)。一旦連接池中的連接對(duì)象被拿光了,下一個(gè)想要操作數(shù)據(jù)庫(kù)的用戶(hù)必須等待,等待其他用戶(hù)釋放連接對(duì)象,把它放回連接池中,這時(shí)候等待的用戶(hù)才能獲取連接對(duì)象,從而操作數(shù)據(jù)庫(kù)。
數(shù)據(jù)庫(kù)連接池的屬性
通過(guò)設(shè)置連接池的參數(shù)來(lái)控制連接池中的初始連接數(shù)、連接的上下限數(shù)以及每個(gè)連接的最大使用次數(shù)、最大空閑時(shí)間等等
連接對(duì)象初始的數(shù)量:initSize,一開(kāi)始就創(chuàng)建若干個(gè),當(dāng)不夠時(shí)再添加
連接對(duì)象最大數(shù)量:maxSize,添加到最大值則不會(huì)再添加
DBCP連接池
druid連接池
DBCP的使用步驟
步驟一:導(dǎo)包,使用第三方的道具,必須導(dǎo)入相應(yīng)的jar包。
需要導(dǎo)入兩個(gè)jar包:commons-dbcp-1.4.jar包
commons-pool-1.5.6.jar包
c3p0連接池
簡(jiǎn)介:DBCP連接池是開(kāi)源組織Apache軟件基金組織開(kāi)發(fā)的連接池實(shí)現(xiàn)。
事實(shí)上,tomcat服務(wù)器默認(rèn)就會(huì)使用這個(gè)連接池道具。
下載jar包
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
/*
設(shè)置注冊(cè)屬性
* */
private static final String driver ="com.mysql.jdbc.Driver";
private static final String url = "jdbc:mysql://localhost:3306/mybatis";
private static final String user = "root";
private static final String password = "1qazxsw2";
@Test
public void TestPool() throws SQLException {
ComboPooledDataSource comboPooledDataSource=new ComboPooledDataSource();
try {
comboPooledDataSource.setDriverClass(driver);
comboPooledDataSource.setJdbcUrl(url);
comboPooledDataSource.setUser(user);
comboPooledDataSource.setPassword(password);
} catch (PropertyVetoException e) {
e.printStackTrace();
}
for (int i=0;i<8;i++){
Connection connection=comboPooledDataSource.getConnection();
System.out.print(connection);
}
}