各位好,我在优化数据库操作模块,请问大家是如何优化的?说说各自的经验好么?谢谢!
先说说我的系统:
我把一些常用的数据库操作诸如返回ResultSet、执行查询等等操作封装到一个DataOpt类,类的部分代码如下:
///////////////////////////////////////////////////////////////////////
public class DataOpt {
/*** 私有变量声明 ***/
private ResultSet resultSet=null;
private Statement statement=null;
private Connection conn=null;
//----------------------------------------------------------------------
/**
* 在构造函数中连接数据库
* @param dbType 数据库类型
* @param userId 用户名
* @param userPwd 口令
*/
public DataOpt() {
try {
conn = ConnectionManager.getConnection();//从连接池中获取连接
ConnectionManager.getStats();
}
catch (Exception ex) {
System.err.println("不能连接数据库!" + ex.getMessage());
}
}
//----------------------------------------------------------------------
/**
* 执行返回记录集的查询
* @param sqlString SQL查询字符串
* @return 返回ResultSet对象
*/
public ResultSet executeQuery(String sqlString) {
statement = null;
resultSet = null;
try {
statement = conn.createStatement();
resultSet = statement.executeQuery(sqlString);
}
catch (SQLException ex) {
System.err.println("executeQuery()出错:" + ex.getMessage());
}
finally{
try {
if (statement != null) {
statement.close();
statement=null;
}
}
catch (SQLException ex1) {
System.err.println("executeQuery() error!");
}
}
return resultSet;
}
///////////////////////////////////////////////////////////////////////
我现在比较困扰的问题是,每次操作数据库都要实例化这个类,是不是很浪费资源?能否在一个class里面只实例化一次这个数据库操作类?如果不行,应该如何优化?
我看到有的代码里面将public ResultSet executeQuery(String sqlString) 写成public synchronized ResultSet executeQuery(String sqlString) ,请问有必要么?谢谢