一种方法是在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相对应:
1 import javax.naming.Context; 2 import javax.naming.InitialContext; 3 import javax.naming.NamingException; 4 import javax.sql.DataSource; 5 public class DBPool { 6 priavate static DataSource ds=null; 7 public static void init(){ 8 try { 9 Context initCtx = new InitialContext(); 10 Context envCtx = (Context) initCtx.lookup("java:comp/env"); 11 DataSource ds = (DataSource) envCtx.lookup("jdbc/connectDB"); 12 if (ds==null) 13 log.error("Datasource:dhcc为配置"); 14 initCtx.close(); 15 envCtx.close(); 16 } catch (NamingException ex) { 17 ex.printStackTrace(); 18 } 19 } 20 public static Connection getConnection() throws SQLException{ 21 Connection conn = null; 22 if (ds==null) 23 init(); 24 try { 25 conn = ds.getConnection(); 26 conn.setAutoCommit(false); 27 return conn; 28 } catch (SQLException e) { 29 30 } 31 } 32 }
时间: 2024-10-09 06:18:05