nos*_*nos 5 java refactoring jdbc
我有太多方法可以反复做类似的事情
Statement stmt = null;
ResultSet rstmt = null;
try {
stmt = conn.createStatement();
rstmt = stmt.executeQuery(...);
while (rstmt.next()) {
//handle rows
}
} catch (SQLException e) {
//handle errors
} finally {
try {rstmt.close();} catch (SQLException ex) {}
try {stmt.close();} catch (SQLException ex) {}
}
Run Code Online (Sandbox Code Playgroud)
语句和结果集的这种设置/拆除/清理是重复的,并隐藏有趣的代码片段.
是否有任何模式或习惯用于处理此问题(不引入任何外部框架)?
您可以创建一个接收 SQL 查询的方法和一个处理ResultSet
. 例如:
private void executeSql(String sql, ResultSetHandler handler) {
Statement stmt = null;
ResultSet rstmt = null;
try {
stmt = conn.createStatement();
rstmt = stmt.executeQuery(sql);
while (rstmt.next()) {
handler.handle(rstmt);
}
}
catch (SQLException e) {
//handle errors
}
finally {
try {rstmt.close();} catch (SQLException ex) {}
try {stmt.close();} catch (SQLException ex) {}
}
}
Run Code Online (Sandbox Code Playgroud)
作为ResultSetHandler
一个接口:
public interface ResultSetHandler {
void handle(ResultSet rs) throws SQLException;
}
Run Code Online (Sandbox Code Playgroud)
并且您可以创建实现该接口的匿名类的对象,因此它不会太混乱。
归档时间: |
|
查看次数: |
1659 次 |
最近记录: |