【学习&讨论】一个类设计的问题,不看的一定后悔,大家一起学习!
请问下面两种方式有何区别,各自的优点和缺点是什么?
//第一种,为每个方法创建一个Connection
public class TestA
{
private Connection getConnection()
{
Class.forName( "... ");
Connection conn = DriverManager.getConnection( "... ");
return conn;
}
public void methodA()
{
Connection conn = getConnection();
...
conn.close();
}
public void methodB()
{
Connection conn = getConnection();
...
conn.close();
}
}
//第二种,创建一个Connection实例变量,供所有的方法调用
public class TestB
{
private Connection conn;
public Test()
{
Class.forName( "... ");
this.conn = DriverManager.getConnection( "... ");
}
public void methodA()
{
...
Statement st = this.conn.createStatement();
...
this.conn.close();
}
public void methodB()
{
...
Statement st = this.conn.createStatement();
...
this.conn.close();
}
}
[解决办法]
第一种,方法之间使用独立的数据库连接,
第二种,设计上存在问题,methodA和methodB应该是共享一个连接,但是又在调用各自方法之后把连接给关闭了,下一个方法调用的时候连接已经关闭,数据库操作明显会出错,数据库连接的关闭操作应该独立出来,也不是由methodA和methodB来调用(既然他们也没有创建连接),有点数据库连接池的味道,只不过只有一个连接
[解决办法]
第一种方法每次调用都要建立连接,比较消耗时间,所以一般都是建立一个连接后重复使用,就是你的第二种方法. 不过this.conn.close();应该去掉,放到finally块中关闭连接
[解决办法]
第二种方法完全错误,同一个连接建立一次关闭多次,
第一种是对的,但是有性能问题,建议使用连接池
[解决办法]
001 import java.io.*;
002 import java.sql.*;
003 import java.util.*;
004 import java.util.Date;
005
006 /**
007 * 管理类DBConnectionManager支持对一个或多个由属性文件定义的数据库连接
008 * 池的访问.客户程序可以调用getInstance()方法访问本类的唯一实例.
009 */
010 public class DBConnectionManager {
011 static private DBConnectionManager instance; // 唯一实例
012 static private int clients;
013
014 private Vector drivers = new Vector();
015 private PrintWriter log;
016 private Hashtable pools = new Hashtable();
017
018 /**
019 * 返回唯一实例.如果是第一次调用此方法,则创建实例
020 *
021 * @return DBConnectionManager 唯一实例
022 */
023 static synchronized public DBConnectionManager getInstance() {
024 if (instance == null) {
025 instance = new DBConnectionManager();
026 }
027 clients++;
028 return instance;
029 }
030
031 /**
032 * 建构函数私有以防止其它对象创建本类实例
033 */
034 private DBConnectionManager() {
035 init();
036 }
037
038 /**
039 * 将连接对象返回给由名字指定的连接池
040 *
041 * @param name 在属性文件中定义的连接池名字
042 * @param con 连接对象
043 */
044 public void freeConnection(String name, Connection con) {
045 DBConnectionPool pool = (DBConnectionPool) pools.get(name);
046 if (pool != null) {
047 pool.freeConnection(con);
048 }
049 }
050
051 /**
052 * 获得一个可用的(空闲的)连接.如果没有可用连接,且已有连接数小于最大连接数
053 * 限制,则创建并返回新连接
054 *
055 * @param name 在属性文件中定义的连接池名字
056 * @return Connection 可用连接或null
057 */
058 public Connection getConnection(String name) {
059 DBConnectionPool pool = (DBConnectionPool) pools.get(name);
060 if (pool != null) {
061 return pool.getConnection();
062 }
063 return null;
064 }
065
066 /**
067 * 获得一个可用连接.若没有可用连接,且已有连接数小于最大连接数限制,
068 * 则创建并返回新连接.否则,在指定的时间内等待其它线程释放连接.
069 *
070 * @param name 连接池名字
071 * @param time 以毫秒计的等待时间
072 * @return Connection 可用连接或null
073 */
074 public Connection getConnection(String name, long time) {
075 DBConnectionPool pool = (DBConnectionPool) pools.get(name);
076 if (pool != null) {
077 return pool.getConnection(time);
078 }
079 return null;
080 }
081
082 /**
083 * 关闭所有连接,撤销驱动程序的注册
084 */
085 public synchronized void release() {
086 // 等待直到最后一个客户程序调用
087 if (--clients != 0) {
088 return;
089 }
090
091 Enumeration allPools = pools.elements();
092 while (allPools.hasMoreElements()) {
093 DBConnectionPool pool = (DBConnectionPool) allPools.nextElement();
094 pool.release();
095 }
096 Enumeration allDrivers = drivers.elements();
097 while (allDrivers.hasMoreElements()) {
098 Driver driver = (Driver) allDrivers.nextElement();
099 try {
100 DriverManager.deregisterDriver(driver);
101 log( "撤销JDBC驱动程序 " + driver.getClass().getName()+ "的注册 ");
102 }
103 catch (SQLException e) {
104 log(e, "无法撤销下列JDBC驱动程序的注册: " + driver.getClass().getName());
105 }
106 }
107 }
108
109 /**
110 * 根据指定属性创建连接池实例.
111 *
112 * @param props 连接池属性
113 */
114 private void createPools(Properties props) {
115 Enumeration propNames = props.propertyNames();
116 while (propNames.hasMoreElements()) {
117 String name = (String) propNames.nextElement();
118 if (name.endsWith( ".url ")) {
119 String poolName = name.substring(0, name.lastIndexOf( ". "));
120 String url = props.getProperty(poolName + ".url ");
121 if (url == null) {
122 log( "没有为连接池 " + poolName + "指定URL ");
123 continue;
124 }
125 String user = props.getProperty(poolName + ".user ");
126 String password = props.getProperty(poolName + ".password ");
127 String maxconn = props.getProperty(poolName + ".maxconn ", "0 ");
128 int max;
129 try {
130 max = Integer.valueOf(maxconn).intValue();
131 }
132 catch (NumberFormatException e) {
133 log( "错误的最大连接数限制: " + maxconn + " .连接池: " + poolName);
134 max = 0;
135 }
136 DBConnectionPool pool =
137 new DBConnectionPool(poolName, url, user, password, max);
138 pools.put(poolName, pool);
139 log( "成功创建连接池 " + poolName);
140 }
141 }
142 }
143
144 /**
145 * 读取属性完成初始化
146 */
147 private void init() {
148 InputStream is = getClass().getResourceAsStream( "/db.properties ");
149 Properties dbProps = new Properties();
150 try {
151 dbProps.load(is);
152 }
153 catch (Exception e) {
154 System.err.println( "不能读取属性文件. " +
155 "请确保db.properties在CLASSPATH指定的路径中 ");
156 return;
157 }
158 String logFile = dbProps.getProperty( "logfile ", "DBConnectionManager.log ");
159 try {
160 log = new PrintWriter(new FileWriter(logFile, true), true);
161 }
162 catch (IOException e) {
163 System.err.println( "无法打开日志文件: " + logFile);
164 log = new PrintWriter(System.err);
165 }
166 loadDrivers(dbProps);
167 createPools(dbProps);
168 }
169
170 /**
171 * 装载和注册所有JDBC驱动程序
172 *
173 * @param props 属性
174 */
175 private void loadDrivers(Properties props) {
176 String driverClasses = props.getProperty( "drivers ");
177 StringTokenizer st = new StringTokenizer(driverClasses);
178 while (st.hasMoreElements()) {
179 String driverClassName = st.nextToken().trim();
180 try {
181 Driver driver = (Driver)
182 Class.forName(driverClassName).newInstance();
183 DriverManager.registerDriver(driver);
184 drivers.addElement(driver);
185 log( "成功注册JDBC驱动程序 " + driverClassName);
186 }
187 catch (Exception e) {
188 log( "无法注册JDBC驱动程序: " +
189 driverClassName + ", 错误: " + e);
190 }
191 }
192 }
193
194 /**
195 * 将文本信息写入日志文件
196 */
[解决办法]
第1种方法勉强可以采用
第2中设计根本是不正确的~,不知道设计者出于哪种目的这样设计
[解决办法]
恩第2种设计不正确.
[解决办法]
学习学习
[解决办法]
第2种根本看不明白!!太菜了!!5555
[解决办法]
up
[解决办法]
按照楼住的调用方式,两种方式完全相同
[解决办法]
up
[解决办法]
都不好~
[解决办法]
数据库的连接数也是有限的资源,最好采用连接池
[解决办法]
连接池