日期:2014-05-16 浏览次数:20551 次
// ...
Connection connA = DbUtil.getConnA();
Connection connB = DbUtil.getConnB();
try {
// ...
} catch (Exception ex) {
// ...
} finally {
connA.close();
connB.close();
}
// ...
} finally {
try {
connA.close();
} catch (Exception ex) {
}
try {
connB.close();
} catch (Exception ex) {
}
}
}
// ...
} finally {
DbUtil.close(connA);
DbUtil.close(connB);
}
}
// ...
public final class DbUtil
{
private DbUtil()
{
}
public static void close(Connection conn)
{
try {
conn.close();
} catch (Exception ex) {
}
}
}
// ...
} finally {
DbUtil.close(connA);
DbUtil.close(connA); // C + P 后遗症,忘记修改变量名了
}
}
// ...
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* DbAdapter
* 数据库访问接口类
*/
public abstract class DbAdapter
{
/**
* 处理sql,并根据要求执行数据操作或查询
*/
static Object process(Connection conn, String sql, DbParamInjector injector, DbReader reader) throws SQLException
{
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
pstmt = conn.prepareStatement(sql);
if (injector != null) {
if (reader != null) {
injector.setParams(pstmt);
rs = pstmt.executeQuery();
return reader.read(rs);
} else {
do {
injector.setParams(pstmt);
pstmt.execute();
} while (injector.hasNext());
return null;
}
} else {
if (reader != null) {
rs = pstmt.executeQuery();
return reader.read(rs);
} else {
pstmt.execute();
return null;
}
}
} finally {
// 释放数据库资源
DBUtil.