这里以MySQL为例:
首先是conf目录下的server.xml
GlobalNamingResources中添加:
<Resource
name="java/mysql/test "
type="javax.sql.DataSource"
password="root"
driverClassName="com.mysql.jdbc.Driver"
maxIdle="2"
maxWait="5000"
username="root"
url="jdbc:mysql://127.0.0.1:3306/test"
maxActive="20"/>
在content.xml中添加:
<ResourceLink
name="java/mysql/test "
type="javax.sql.DataSource"
global="java/mysql"/>
由于定义的是global的,所以不需要 在所在应用中的web.xml中添加:
<resource-ref>
<description>MySQL DB Connection Pool</description>
<res-ref-name>java/mysql/test </res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
注意保持黑体部分的一致性,这样在程序中就可以使用了:
import java.io.Serializable;
import java.sql.*;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import javax.sql.DataSource;
public class ConnectionPool implements Serializable{
private String URI = "java:comp/env/java/mysql";
private DataSource dataSource;
private static ConnectionPool connectionpool;
private Connection connection;
private InitialContext getInitialContext()throws NamingException{
return new InitialContext();
}
public Connection getConnection()throws NamingException, SQLException{
if(dataSource == null){
InitialContext initialcontext = getInitialContext();
Object obj = initialcontext.lookup(URI);
dataSource = (DataSource)PortableRemoteObject.narrow(obj, javax.sql.DataSource.class);
initialcontext.close();
}
connection = dataSource.getConnection();
return connection;
}
public static void main(String[] args) {
try{
Connection con = connectionpool.getConnection();//获取连接
PreparedStatement pst = con
.prepareStatement("select count(*) from test.user;");
ResultSet rs = pst.executeQuery();
while(rs.next()){
System.out.println(rs.getString(1));
}
} catch (Exception e) {
e.printStackTrace();
}
connectionpool.close();
}
public void close(){
try {
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}