本文主要講述Tomcat自帶的連接池怎麼使用
說句題外話,博主在jar包的選擇這塊踩了很多坑,以下是經驗之談:
我採用的是數據庫是oracle,本文也需要ojdbc.jar這一個jar包。但是!我發現部分ojdbc的版本與該數據源不兼容,經過博主的嘗試,ojdbc7能過完美運行。
下面開始講述使用步驟:
1.在Tomcat中配置context.xml
<!--tomcat-dbcp-->
<Resource name="lulu" auth="Container"
type="javax.sql.DataSource" maxActive="400"
maxIdle="20" maxWait="5000" username="scott" password="tiger"
driverClassName="oracle.jdbc.driver.OracleDriver" url="jdbc:oracle:thin:@127.0.0.1:1521:ORCL" />
2.在項目的web.xml中配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<resource-ref>
<res-ref-name>lulu</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
3.使用/測試
public class Test{
public static Connection connection = null;
public static void printConnection() throws ClassNotFoundException, SQLException {
Class.forName("oracle.jdbc.OracleDriver");
try{
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("java:comp/env/lulu");
connection = ds.getConnection();
System.out.println(connection);
}catch(NamingException e){
e.printStackTrace();
}
// return connection = DriverManager.getConnection(URL,USERNAME,PWD);
}
public static void main(){
printConnection();
}
}