JDBC数据源(DataSource)的简单实现
前言:
数据源技术是Java操作数据库的一个很关键技术,流行的持久化框架都离不开数据源的应用。
数据源提供了一种简单获取数据库连接的方式,并能在内部通过一个池的机制来复用数据库连接,这样就大大减少创建数据库连接的次数,提高了系统性能。
对于数据源的应用,一般都选择实用开源的数据源或数据库连接池来使用,比如,常见的有DBCP、C3P0、Proxool等等。但用起来有些笨重和麻烦。下面自己手动实现个精简的数据源,代码如下:
1 import org.apache.commons.logging.Log; 2 import org.apache.commons.logging.LogFactory; 3 4 import javax.sql.DataSource; 5 import java.util.Collections; 6 import java.util.LinkedList; 7 import java.sql.Connection; 8 import java.sql.SQLException; 9 import java.sql.DriverManager; 10 import java.io.PrintWriter; 11 12 /** 13 * 一个简单的DataSource实现 14 * 15 * @author leizhimin 2010-1-14 0:03:17 16 */ 17 public class SimpleDateSource implements DataSource { 18 private static Log log = LogFactory.getLog(SimpleDateSource.class); 19 private static final String dirverClassName = "com.mysql.jdbc.Driver"; 20 private static final String url = "jdbc:mysql://127.0.0.1:3306/testdb"; 21 private static final String user = "root"; 22 private static final String pswd = "leizhimin"; 23 //连接池 24 private static LinkedList<Connection> pool = (LinkedList<Connection>) Collections.synchronizedList(new LinkedList<Connection>()); 25 private static SimpleDateSource instance = new SimpleDateSource(); 26 27 static { 28 try { 29 Class.forName(dirverClassName); 30 } catch (ClassNotFoundException e) { 31 log.error("找不到驱动类!", e); 32 } 33 } 34 35 private SimpleDateSource() { 36 } 37 38 /** 39 * 获取数据源单例 40 * 41 * @return 数据源单例 42 */ 43 public SimpleDateSource instance() { 44 if (instance == null) instance = new SimpleDateSource(); 45 return instance; 46 } 47 48 /** 49 * 获取一个数据库连接 50 * 51 * @return 一个数据库连接 52 * @throws SQLException 53 */ 54 public Connection getConnection() throws SQLException { 55 synchronized (pool) { 56 if (pool.size() > 0) return pool.removeFirst(); 57 else return makeConnection(); 58 } 59 } 60 61 /** 62 * 连接归池 63 * 64 * @param conn 65 */ 66 public static void freeConnection(Connection conn) { 67 pool.addLast(conn); 68 } 69 70 private Connection makeConnection() throws SQLException { 71 return DriverManager.getConnection(url, user, pswd); 72 } 73 74 public Connection getConnection(String username, String password) throws SQLException { 75 return DriverManager.getConnection(url, username, password); 76 } 77 78 public PrintWriter getLogWriter() throws SQLException { 79 return null; 80 } 81 82 public void setLogWriter(PrintWriter out) throws SQLException { 83 84 } 85 86 public void setLoginTimeout(int seconds) throws SQLException { 87 88 } 89 90 public int getLoginTimeout() throws SQLException { 91 return 0; 92 } 93 94 public <T> T unwrap(Class<T> iface) throws SQLException { 95 return null; 96 } 97 98 public boolean isWrapperFor(Class<?> iface) throws SQLException { 99 return false; 100 } 101 }
心有猛虎,细嗅蔷薇 转载请注明:https://www.cnblogs.com/ygh1229/