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();
%>