一、配置数据源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