Tomcat8設定資料庫串連池,tomcat8資料庫連接

來源:互聯網
上載者:User

Tomcat8設定資料庫串連池,tomcat8資料庫連接

1、所有的tomcat項目共用一個串連池配置

1.1 修改conf->context.xml檔案,在Context節點下配置

<Resource
name="jdbc/myDataSource"
type="javax.sql.DataSource"
driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
maxIdle="2"
maxWait="5000"
username="sa"
password="xx"
url="jdbc:sqlserver://127.0.0.1\\SQLEXPRESS:1433;DatabaseName=ShopSystem"
maxActive="4"/>

說明:

<!--name:DataSource的名稱-->
<!--type:資料來源對應的java類型,一般設計為javax.sql.DataSource-->
<!--username:資料庫登陸名-->
<!--password:資料庫登陸密碼-->
<!--driverClassName:指定資料庫JDBC驅動程式-->
<!--url:指定資料庫的URL-->
<!--maxIdle:串連池處於空閑狀態的資料庫連接的最大數目,取0表示不受限制-->
<!--maxWait:串連池中資料庫連接處於空閑狀態的最長時間(以毫秒為單位),取0表示無限制等待時間-->
<!--maxActive:串連池處於活動狀態的資料庫連接的最大數目,去0表示不受限制-->

1.2 修改tomcat的web.xml檔案

在web-app節點下配置:

<resource-ref>
<res-ref-name>jdbc/myDataSource</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>

2、每個Web項目獨立用自己的串連池配置

2.1 在Web項目的META-INF目錄下建立context.xml檔案,內容如下

<?xml version="1.0" encoding="UTF-8"?>
<Context path="/">
<Resource
name="jdbc/myDS"
type="javax.sql.DataSource"
driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
maxIdle="2"
maxWait="5000"
username="sa"
password="xx"
url="jdbc:sqlserver://127.0.0.1\\SQLEXPRESS:1433;DatabaseName=ShopSystem"
maxActive="4"/>
</Context>

2.2  修改Web項目的WEB-INF目錄下的web.xml檔案

在web-app節點下配置:

<resource-ref>
<res-ref-name>jdbc/myDS</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>

3、不管用上面哪種串連池,都需要把資料庫驅動jar檔案拷貝到tomcat的lib目錄下

4、測試程式

<%
Context initContext=new InitialContext();
Context envContext=(Context)initContext.lookup("java:comp/env");
DataSource ds=(DataSource)envContext.lookup("jdbc/myDataSource");
Connection connection=ds.getConnection();
Statement statement=connection.createStatement();
ResultSet resultSet=statement.executeQuery("select * from admin");
while(resultSet.next()){
out.print(resultSet.getString("a_name"));
out.print("<br />");
}
resultSet.close();
statement.close();
connection.close();
%>

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.