我有一个无状态会话bean,其方法重复用于在纯JDBC连接中运行SQL查询.为了避免过于频繁地打开和关闭连接,我提出了以下方法,并想知道这是否是一个好习惯:
我在注释@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
}
Run Code Online (Sandbox Code Playgroud)
最好的解决方案是使用DataSource
@Resource(mappedName="java:/DefaultDS")
DataSource dataSource;
public String runTheQuery(String sql) throws SQLException
Connection con = dataSource.getConnection();
try {
...
} finally {
con.close();
}
}
Run Code Online (Sandbox Code Playgroud)