使用Commons-Pool写的数据库连接池
2008-01-05 19:30:00 来源:WEB开发网核心提示:1.数据库链接的接口类:DatabaseConnection package net.pingsoft.kelefa.pool;import java.sql.*;import javax.sql.*;import com.wish.JDBC.WConnection;import org.apache.commons.
1.数据库链接的接口类:DatabaseConnection
package net.pingsoft.kelefa.pool;2. 数据库链接工厂类ConnectionFactory
import java.sql.*; import javax.sql.*; import com.wish.JDBC.WConnection; import org.apache.commons.pool.*; import org.apache.commons.pool.impl.*; /** * 数据库链接的接口类.直接调用静态方法getDBConnection()取得Connection对象. * 相关的参数由PoolConfigServlet类根据web.xml设置,所以web.xml需要注册PoolConfigServlet * * Copyright: Copyright (c) 2004 * @author kelefa yang * @version 1.0 * @see PoolConfigServlet */ public class DatabaseConnection { /** 数据库的用户名 */ public static String USER = "sa"; /** 数据库的用密码 */ public static String PASS = "yf1"; /** 数据库的启动程序类名 */ public static String DBDRIVER = "com.microsoft.jdbc.sqlserver.SQLServerDriver"; /** 数据库的链接地址 */ public static String DBURL = "jdbc:microsoft:sqlserver://192.9.200.23:1433;DatabaseName=FC"; /** 是否使用jndi */ public static boolean useJNDI = false; /** jndi的名字,useJNDI==false时无效 */ public static String JNDI = "wishJndi"; /** * 是否对数据库链接进行编码转换 * @dePRecated 没有进行测试,应该直接设置数据库或在链接url加上编码参数 */ public static boolean convertConnetion = false; /** 是否缓冲链接 */ public static boolean POOL_CONNECTION = false; /** * 没有必要生成实例 */
private DatabaseConnection() {}
/** * 根据相应参数取回实际的数据库链接. * 假如useJNDI为真,根据JNDI名字从数据源取链接;否则直接从jdbc取链接. * 假如convertConnetion为真,对链接再封装,实现编码的转换. * @throws Exception 当useJNDI==false,并且USER,PASS,DBDRIVER,DBURL其中一个为空时 * 抛出"DatabaseConnection didn't init!!"异常 * @return Connection 数据库链接,取不到时返回null */ static Connection getConnection() throws Exception { Connection conn = null; if( !useJNDI ) { if( ( USER == null ) ( PASS == null ) ( DBDRIVER == null ) ( DBURL == null ) ) throw new Exception( "DatabaseConnection didn't init!!" ); Class.forName( DBDRIVER ); conn = DriverManager.getConnection( DBURL, USER, PASS ); } else { DataSource ds = ServiceLocator.getInstance().getDataSource( JNDI ); conn = ds.getConnection(); } if( convertConnetion && conn != null ) return new WConnection( conn ); else return conn; }
/** 链接池工厂 */ private static GenericObjectPoolFactory poolFactory = new GenericObjectPoolFactory( new ConnectionFactory() ); /** 数据库链接池 */ private static ObjectPool pool = poolFactory.createPool();
/** * if POOL_CONNECTION is true, return the pooled connetion. * POOL_CONNECTION will be set in Class PoolConfigServlet when webapp start, * you can change the value in web.xml. ** <init-param> * <param-name>poolConnection</param-name> * <param-value>true</param-value> * </init-param> ** @throws Exception * @return Connection */ public static Connection getDBConnection() throws Exception { if( POOL_CONNECTION ) { Object obj = pool.borrowObject(); if( null == obj ) return null; PoolableConnection conn = ( PoolableConnection )obj; conn.setPool( pool ); return conn; } else return getConnection(); } }
package net.pingsoft.kelefa.pool;
更多精彩
赞助商链接