對象復用池()
為了能夠從代碼層面更好地理解數據庫連接池讀者可以仔細閱讀以下代碼
public static void main(String[] argv) {
try {
ClassforName(commysqljdbcDriver)
DataSource unpooled = DataSources
unpooledDataSource(
jdbc:mysql://:/test
root )
DataSource pooled = DataSourcespooledDataSource(unpooled)
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
con = pooledgetConnection() //第一次取得數據庫連接
Systemoutprintln(con Class Type is:+congetClass()getName())
Object o=getInnter(con) //取得內部的實際數據庫連接
Systemoutprintln(Inner con Class Type is:+ogetClass()
getName())
stmt = concreateStatement()
rs = stmtexecuteQuery(SELECT * FROM user)
while (rsnext())
Systemoutprintln(Data from DB:+rsgetString())
rsclose()
stmtclose()
conclose()
Threadsleep() //等待連接返回池中
con = pooledgetConnection() //第二次取得數據庫連接
Object o=getInnter(con)
if(o==o) //相同則說明數據庫連接被復用
Systemoutprintln(o and o is same object)
stmt = concreateStatement()
rs = stmtexecuteQuery(SELECT * FROM user)
while (rsnext())
Systemoutprintln(Data from DB:+rsgetString())
rsclose()
stmtclose()
conclose()
} catch (Exception e) {
eprintStackTrace()
}
}
[] []
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27799.html