一种方法是在conf/context.xml文件中配置,配置oracle连接池的一个例子的context内容如下:
<?xml version='1.0' encoding='utf-8'?>
<Context>
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<Resource name="jdbc/connectDB" author="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="1000" username="usr" password="pwd"
driverClassName="oracle.jdbc.OracleDriver" url="jdbc:oracle:thin:@192.168.0.13:1521:DB" />
</Context>
代码中使用如下,其中lookup()中字符串与context.xml中Resource name相对应:
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class DBPool {
priavate static DataSource ds=null;
public static void init(){
try {
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource) envCtx.lookup("jdbc/connectDB");
if (ds==null)
log.error("Datasource:dhcc为配置");
initCtx.close();
envCtx.close();
} catch (NamingException ex) {
ex.printStackTrace();
}
}
public static Connection getConnection() throws SQLException{
Connection conn = null;
if (ds==null)
init();
try {
conn = ds.getConnection();
conn.setAutoCommit(false);
return conn;
} catch (SQLException e) { }
}
}