日期:2014-05-16 浏览次数:20450 次
前几天写了个数据库链接池类,但有个问题使终解决得不太满意,所以贴出来让大家帮我想想办法啦.....
首先写了个ConnectionFactory接口类,代码如下:
package com.luoyu.persistence; public interface ConnectionFactory { public static final String CONNECTION_USERNAME = "connection.username"; public static final String CONNECTION_PASSWORD = "connection.password"; public static final String CONNECTION_URL = "connection.url"; public static final String DRIVER_CLASS = "driver.class"; }?
package com.luoyu.persistence; import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; import oracle.jdbc.pool.OracleDataSource; public class DataSourceConnectionFactory implements ConnectionFactory { private static DataSourceConnectionFactory instance; private static Properties config; @SuppressWarnings( { "unchecked", "unused" }) private static Class driver; private static OracleServerDataSource Orads; private static ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>(); static{ init(); } public static void init(){ try { config = new Properties(); config.load(ConnectionFactory.class .getResourceAsStream("/config.properties")); Orads= new OracleDataSource(); driver = Class.forName(config.getProperty(DRIVER_CLASS)); Orads.setUser(config.getProperty(CONNECTION_USERNAME)); SQLds.setPassword(config.getProperty(CONNECTION_PASSWORD)); Orads.setURL(config.getProperty(CONNECTION_URL)); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } private static DataSourceConnectionFactory getInstance() { if (instance == null) { instance = new DataSourceConnectionFactory(); } return instance; } public static void closeConnect() throws SQLException { if (!threadLocal.get().isClosed() && threadLocal.get() != null) { threadLocal.get().close(); } threadLocal.set(null); } public static void destory() { instance = null; config = null; driver = null; Orads= null; } private Connection getConnect() throws SQLException { if (threadLocal.get() == null || threadLocal.get().isClosed()) { threadLocal.set(Orads.getConnection()); } return threadLocal.get(); } public static Connection getConnection()throws SQLException{ Connection connection = getInstance().getConnect(); return connection; } }?
connection.username=system connection.password=admin connectino.url=jdbc:oracle:thin://localhost:1521:orcl driver.class=oracle.jdbc.driver.OracleDriver?
?