一、所需软件 Tomact+Mysql+ecplice;
演示的版本为apache-tomcat-7.0.35+eclipse-jee-juno-SR1-win32.+mysql-5.6.15-win32;
二、1。创建web项目
2。创建服务器
3。配置web项目中的web.xml文件
在<web-app>与</web-app>之间添加代码如下:
<resource-ref> <!-- 资源工厂配置->
<description>DB Connection</description> <!-- 描述->
<res-ref-name>jdbc/mysql</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
<!-- 描述->
<res-ref-name>jdbc/mysql</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
4。配置服务器整的context.xml文件
在<Context>与</Context>之间添加代码如下:
<Resource name="jdbc/mysql" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="root" password="1234" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/javatest"/>
Resource属性说明:
name:指定Resource的JNDI名字。
auth:指定管理Resource的Manager,它有两个可选值:Container和Application。Container表示由容器来创建和管理Resource,Application表示由web应用来创建和管理Resource。
type: 指定Resource的Java类名。
maxActive:指定数据库连接池中处于活动状态的数据库连接的最大数目,取值为0,表示不受限制。
maxIdle:指定数据库连接池中处于空闲状态的数据库连接的最大数目,取值为0,表示不受限制。
maxWait:指定数据库连接池中的数据库连接处于空闲状态的最长时间(以毫秒为单位),超过这一时间,将会抛出异常。取值为-1,表示可以无限期等待
username:指定连接数据库的用户名。
password:指定连接数据库的口令。
driverClassName:指定连接数据库的JDBC驱动器中的Driver实现类的名字。
url:指定连接数据库的URL,127.0.0.1是要连接的数据库服务器的ip,3306是数据库服务器端口,BookDB是数据库名称。
5。获取连接池数据
代码如下:
private static Context context=null;
private static DataSource ds = null;
private static Connection conn = null;
public static Connection getCon(){
try {
context = new InitialContext();
} catch (NamingException e) {
System.err.println("连接池上下文不存在! " + e.getMessage());
}
try {
ds = (DataSource)context.lookup("java:comp/env/jdbc/mysql");
} catch (NamingException e) {
System.err.println("数据源没发现! " + e.getMessage());
}
try {
conn = (Connection) ds.getConnection();
} catch (SQLException e) {
System.err.println("获取连接失败! " + e.getMessage());
}
return conn;
}