- <pre class="html" name="code">1.將數據庫驅動程序的JAR文件放在Tomcat的 common/lib 中;
- </pre><pre class="html" name="code">2.在server.xml中設置數據源,以MySQL數據庫爲例,如下:
- 在<GlobalNamingResources> </GlobalNamingResources>節點中加入,
- </pre><pre class="html" name="code"><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"/>
- </pre><pre class="html" name="code">屬性說明:name,數據源名稱,通常取”jdbc/XXX”的格式;
- type,”javax.sql.DataSource”;
- password,數據庫用戶密碼;
- driveClassName,數據庫驅動;
- maxIdle,最大空閒數,數據庫連接的最大空閒時間。超過空閒時間,數據庫連接將被標記爲不可用,然後被釋放。設爲0表示無限制。
- MaxActive,連接池的最大數據庫連接數。設爲0表示無限制。
- maxWait ,最大建立連接等待時間。如果超過此時間將接到異常。設爲-1表示無限制。</pre><pre class="html" name="code">
- 3.在你的web應用程序的web.xml中設置數據源參考,如下:
- 在<web-app></web-app>節點中加入,
- </pre><pre class="html" name="code"><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>
- </pre><pre class="html" name="code"> 子節點說明: </pre><pre class="html" name="code"> description,描述信息;
- res-ref-name,參考數據源名字,同上一步的屬性name;
- res-type,資源類型,”javax.sql.DataSource”;
- res-auth,”Container”;
- res-sharing-scope,”Shareable”;
- </pre><pre class="html" name="code">4.在web應用程序的context.xml中設置數據源鏈接,如下:
- 在<Context></Context>節點中加入,
- </pre><pre class="html" name="code"><ResourceLink
- name="jdbc/DBPool"
- type="javax.sql.DataSource"
- global="jdbc/DBPool"/>
- </pre><pre class="html" name="code">屬性說明:</pre><pre class="html" name="code"> name,同第2步和第3步的屬性name值,和子節點res-ref-name值;
- type,同樣取”javax.sql.DataSource”;
- global,同name值。
- 至此,設置完成,下面是如何使用數據庫連接池。
- </pre><pre class="html" name="code">1.建立一個連接池類,DBPool.java,用來創建連接池,代碼如下:
- <pre class="java" name="code">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;
- }
- } </pre><br>
- <pre></pre>
- <pre class="html" name="code">2.在要用到數據庫操作的類或jsp頁面中,用DBPool.getPool().getConnection(),獲得一個Connection對象,就可以進行數據庫操作,最後別忘了對Connection對象調用close()方法,注意:這裏不會關閉這個Connection,而是將這個Connection放回數據庫連接池。
- </pre><br>
- <pre></pre>
- <pre></pre>
- </pre>
tomcat 中設置連接池
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.