JDNI使用小记 < Resource name ="jdbc/mysql" auth ="Container" type ="javax.sql.DataSource" maxActive ="100" maxIdle ="30" maxWait ="60" wait_timeout ="18800" timeBetweenEvictionRunsMillis ="300000" minEvictableIdleTimeMillis ="600000" username ="root" password ="root" driverClassName ="com.mysql.jdbc.Driver" url ="jdbc:mysql://localhost:3306/studentjxy?comautoReconnect=true&failOverReadOnly=false" removeAbandoned ="true" removeAbandonedTimeout ="60" logAbandoned ="true" /> package db; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; public class DBCache { private InitialContext ic ; private Map<String, DataSource> cache ; private static DBCache instance = new DBCache(); private DBCache() { try { ic = new InitialContext(); } catch (NamingException e) { e.printStackTrace(); } cache = Collections.synchronizedMap( new HashMap<String, DataSource>()); } public static DBCache getInstance() { return instance ; } public Connection getDBConn(String dataSourceName) throws SQLException, NamingException { Connection conn = null ; conn = getDataSource(dataSourceName).getConnection(); return conn; } public DataSource getDataSource(String dataSourceName) throws NamingException { if (cache .containsKey(dataSourceName)) { return cache .get(dataSourceName); } else { DataSource newDataSource = (DataSource) ic .lookup(dataSourceName); cache .put(dataSourceName, newDataSource); return newDataSource; } } public void removeDateSouceOffCache(String dataSourceName) { try { DataSource ds = cache .get(dataSourceName); ds.getConnection().close(); cache .remove(dataSourceName); } catch (Exception ex) { } } public static void freeConn(Connection conn) { freeConn(conn, null, null ); } public static void freeConn(Connection connection, Statement statement) { freeConn(connection, statement, null); } public static void freeConn(Connection conn, Statement ps, ResultSet rs) { try { try { if (rs != null) rs.close(); } finally { try { if (ps != null) ps.close(); } finally { if (conn != null) conn.close(); } } } catch (SQLException ex) { ex.printStackTrace(); } } } package db; import java.sql.Connection; import java.sql.SQLException; import javax.naming.NamingException; public class DBManager { public Connection getConnection() { DBCache db = DBCache. getInstance(); Connection conn = null ; try { conn = db.getDBConn( "java:comp/env/jdbc/mysql" ); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NamingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return conn; } }