1.將數(shù)據(jù)庫驅(qū)動(dòng)程序的jar文件放在tomcat的 common/lib 中;
2.在server.xml中設(shè)置數(shù)據(jù)源,以mysql數(shù)據(jù)庫為例,如下:
在<globalnamingresources> </globalnamingresources>節(jié)點(diǎn)中加入,
<resource
name="jdbc/dbpool"
type="javax.sql.datasource"
password="root"
driverclassname="com.mysql.jdbc.driver"
maxidle="2"
maxwait="5000"
username="root"
url="jdbc:mysql://127.0.0.1:3306/test"
maxactive="4"/>
屬性說明:name,數(shù)據(jù)源名稱,通常取”jdbc/xxx”的格式;
type,”javax.sql.datasource”;
password,數(shù)據(jù)庫用戶密碼;
driveclassname,數(shù)據(jù)庫驅(qū)動(dòng);
maxidle,最大空閑數(shù),數(shù)據(jù)庫連接的最大空閑時(shí)間。超過空閑時(shí)間,數(shù)據(jù)庫連
接將被標(biāo)記為不可用,然后被釋放。設(shè)為0表示無限制。
maxactive,連接池的最大數(shù)據(jù)庫連接數(shù)。設(shè)為0表示無限制。
maxwait ,最大建立連接等待時(shí)間。如果超過此時(shí)間將接到異常。設(shè)為-1表示
無限制。
3.在你的web應(yīng)用程序的web.xml中設(shè)置數(shù)據(jù)源參考,如下:
在<web-app></web-app>節(jié)點(diǎn)中加入,
<resource-ref>
<description>mysql db connection pool</description>
<res-ref-name>jdbc/dbpool</res-ref-name>
<res-type>javax.sql.datasource</res-type>
<res-auth>container</res-auth>
<res-sharing-scope>shareable</res-sharing-scope>
</resource-ref>
子節(jié)點(diǎn)說明: description,描述信息;
res-ref-name,參考數(shù)據(jù)源名字,同上一步的屬性name;
res-type,資源類型,”javax.sql.datasource”;
res-auth,”container”;
res-sharing-scope,”shareable”;
4.在web應(yīng)用程序的context.xml中設(shè)置數(shù)據(jù)源鏈接,如下:
在<context></context>節(jié)點(diǎn)中加入,
<resourcelink
name="jdbc/dbpool"
type="javax.sql.datasource"
global="jdbc/dbpool"/>
屬性說明:name,同第2步和第3步的屬性name值,和子節(jié)點(diǎn)res-ref-name值;
type,同樣取”javax.sql.datasource”;
global,同name值。
至此,設(shè)置完成,下面是如何使用數(shù)據(jù)庫連接池。
1.建立一個(gè)連接池類,dbpool.java,用來創(chuàng)建連接池,代碼如下:
import javax.naming.context;
import javax.naming.initialcontext;
import javax.naming.namingexception;
import javax.sql.datasource;
public class dbpool {
private static datasource pool;
static {
context env = null;
try {
env = (context) new initialcontext().lookup("java:comp/env");
pool = (datasource)env.lookup("jdbc/dbpool");
if(pool==null)
system.err.println("'dbpool' is an unknown datasource");
} catch(namingexception ne) {
ne.printstacktrace();
}
}
public static datasource getpool() {
return pool;
}
}
2.在要用到數(shù)據(jù)庫操作的類或jsp頁面中,用dbpool.getpool().getconnection(),獲得一個(gè)connection對(duì)象,就可以進(jìn)行數(shù)據(jù)庫操作,最后別忘了對(duì)connection對(duì)象調(diào)用close()方法,注意:這里不會(huì)關(guān)閉這個(gè)connection,而是將這個(gè)connection放回?cái)?shù)據(jù)庫連接池。
新聞熱點(diǎn)
疑難解答
圖片精選