数据库连接池
1.数据库连接池用来干啥?
像打开关闭数据库连接这种和数据库的交互可能是很费时的,尤其是当客户端数量增加的时候,会消耗大量的资源,成 本是非常高的。可以在应用服务器启动的时候建立很多个数据库连接并维护在一个池中。连接请求由池中的连接提供。在 连接使用完毕以后,把连接归还到池中,以用于满足将来更多的请求。2.数据库连接池步骤:
<1>copy相对应的数据库jar到Tomcat/lib
<2>添加以下配置信息到conf/context.xml
<Resource name="jdbc/news" auth="Container"
type="javax.sql.DataSource" maxActive="100"
maxIdle="30" maxWait="10000" username="scott" password="tiger"
driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@localhost:1521:orcl"
/>
<Resource name="jdbc/TestDB"
auth="Container"
type="javax.sql.DataSource"
username="root"
password="password"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/text?autoReconnect=true"
maxTotal="8"
maxIdle="4"/>
<3>配置web.xml
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/TestDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
<4>测试
Context context=new InitialContext();
Context envContext=(Context)context.lookup("java:/comp/env");
DataSource dataSource=(DataSource)envContext.lookup("jdbc/TestDB");
Connection conn=dataSource.getConnection();
out.print(conn);
3.也可以到tomcat官网去看相关文档。