我有一个无状态会话bean,它的一个方法被重复用于在纯JDBC连接中运行SQL查询。为避免频繁地打开和关闭连接,我提出了以下方法,并想知道这是否是一种好的做法:无状态会话bean中的高效JDBC连接管理
我在注释@PostConstruct的方法中打开一次连接,并在注释的另一个方法中关闭连接@PreDestroy
该代码工作正常,没有明显的内存泄漏或我知道的任何问题 - 只是想知道如果更有经验的开发人员会同意,如果这是一个很好的做法。
@PostConstruct
public void initBean() {
try {
conn = Connector.getConnection();
} catch (Exception e) {
// Handle errors for Class.forName
e.printStackTrace();
}
}
public String runTheQuery(String sql) {
String result ="";
try {
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
result = rs.getString(1);
rs.close();
pstmt.close();
} catch (SQLException se) {
// Handle errors for JDBC
}
return result;
}
@PreDestroy
public void endingTitles() {
System.out.println("Closing the JDBC connection...");
try {
rs.close();
conn.close();
pstmt.close();
} catch (SQLException se) {
// Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
// finally block used to close resources
try {
if (pstmt != null)
pstmt.close();
} catch (SQLException se2) {
}// nothing we can do
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}// end finally try
}// end try
}
这不会避免每次调用runTheQuery()方法时打开一个连接 - 在这种情况下,该方法意味着在控制器类的循环中重复调用100000次。 – fledglingCoder
DataSources通常是连接池,它们重新使用连接,con.close只是将其返回到池。 –