一、配置數據源Resource ,多種方式:html
a)存爲context.xml,於項目WebRoot/META-INF下;java
b)存爲項目名.xml,於$tomcat-home$\conf\Catalina\localhost下;sql
c)Resource部分,粘貼於$tomcat-home$\conf\context.xml中數據庫
<Context></Context>
之間;
apache
d)設置爲全局鏈接池,Resource 部分粘貼於$tomcat-home$\conf\server.xml,編程
<GlobalNamingResources></GlobalNamingResources>
之間,並在conf/context.xml中
tomcat
<Context></Context>
之間,設置
oracle
<ResourceLink type="javax.sql.DataSource" name="jdbc/pdbqz" global="jdbc/TestDB" />
<?xml version="1.0" encoding="UTF-8"?> <Context> <Resource name="jdbc/pdbqz" auth="Container" type="javax.sql.DataSource" factory="org.apache.tomcat.jdbc.pool.DataSourceFactory" testWhileIdle="true" testOnBorrow="true" testOnReturn="false" validationQuery="SELECT 1" validationInterval="30000" timeBetweenEvictionRunsMillis="30000" maxActive="100" minIdle="10" maxWait="10000" initialSize="10" removeAbandonedTimeout="60" removeAbandoned="true" logAbandoned="true" minEvictableIdleTimeMillis="30000" jmxEnabled="true" jdbcInterceptors="org.apache.tomcat.jdbc.pool.interceptor.ConnectionState; org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer" username="qzdata" password="93411316" driverClassName="oracle.jdbc.driver.OracleDriver" url="jdbc:oracle:thin:@localhost:1521:PDBQZ"/> </Context>
二、數據庫驅動jar包拷貝到tomcat lib中;異步
三、從tomcat lib中拷貝tomcat-jdbc.jar到項目lib,方便編程中調用;jsp
四、異步獲取鏈接:
package db; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.concurrent.Future; import javax.naming.Context; import javax.naming.InitialContext; import org.apache.tomcat.jdbc.pool.DataSource; public class DBConn { public void poolTest() throws Exception{ Connection con = null; Context initCtx=new InitialContext(); Context envCtx=(Context)initCtx.lookup("java:/comp/env"); DataSource datasource=(DataSource)envCtx.lookup("jdbc/pdbqz"); try { Future<Connection> future = datasource.getConnectionAsync(); while(!future.isDone()) { System.out.println("Connection is not yet available. Do some background work"); try { Thread.sleep(100); //simulate work }catch (InterruptedException x) { Thread.currentThread().interrupt(); } } con = future.get(); //should return instantly Statement st = con.createStatement(); ResultSet rs = st.executeQuery("select * from USERINFO"); int cnt = 1; while (rs.next()) { System.out.println((cnt++) + " User:" + rs.getString("userid") + " Password:" + rs.getString("password")); } rs.close(); st.close(); } finally { if (con != null) { try { con.close(); } catch (Exception ignore) { ignore.printStackTrace(); } } } } }
五、jsp中調用該類。
更多信息參考:https://tomcat.apache.org/tomcat-7.0-doc/jdbc-pool.html
http://blog.csdn.net/yp5185423/article/details/8299800