我正在做代码审查,在许多情况下,我发现如果SQL语句返回记录,结果就不会关闭。SQL语句的业务规则仅考虑第一条记录。
下面是我感到困惑的代码,为什么它返回值而不关闭结果集和语句?这条路对吗?
if (rs.next()){
return new Long(rs.getLong(1));
}以下是示例代码:
private static Long <MethodName>
(
oracle.sql.NUMBER[] o_errorCode,
oracle.sql.CHAR[] o_errorText,
Long portA,
Long portZ) throws SQLException
{
String errorMessage = "";
Long[] NROLE = new Long[1];
Long[] pTask = new Long[1];
Long dimObject = null;
Long objectIDA = null;
Long objectIDZ = null;
Long relation = null;
Connection tmpConn = null;
Statement stmt = null;
ResultSet rs = null;
String SQL = null;
try
{
// Retrieve the Epipe circuits that are on the specified ports
stmt = DbUtil.getConn().createStatement();
String query = "Select * from Circuit where ... Order by Id";
rs = stmt.executeQuery(query);
if (rs.next()){
return new Long(rs.getLong(1));
}
rs.close();
stmt.close();
return null;
}
catch (SQLException ex)
{
o_errorCode[0] = new oracle.sql.NUMBER(1);
o_errorText[0] = new oracle.sql.CHAR("SQLException - " + ex.getMessage(),
oracle.sql.CharacterSet.make(oracle.sql.CharacterSet.DEFAULT_CHARSET));
return(null);
}
catch (Exception e)
{
o_errorCode[0] = new oracle.sql.NUMBER(1);
o_errorText[0] = new oracle.sql.CHAR("Exception - " + e.getMessage(), oracle.sql.CharacterSet.make(
oracle.sql.CharacterSet.
DEFAULT_CHARSET));
return(null);
}
}发布于 2014-07-02 22:19:27
不正确,而且由于Java 7在使用try-with-resources时很容易解决:
try (ResultSet rs = statement.executeQuery()) {
if ...
return ...
}if rs.next()可能需要更好的SQL:一种limit或一种MIN(Id)。
这也不是一个好的风格:
JDBC使用一致的风格:PreparedStatement或select from where by.
SELECT FROM WHERE ORDER BY花了很大力气才不需要它。
发布于 2014-07-02 22:18:38
使用finally。
try {
// Retrieve the Epipe circuits that are on the specified ports
stmt = DbUtil.getConn().createStatement();
String query = "Select * from Circuit where ... Order by Id";
rs = stmt.executeQuery(query);
if (rs.next()) {
return new Long(rs.getLong(1));
}
return null;
} catch (SQLException ex) {
} catch (Exception e) {
} finally {
rs.close();
stmt.close();
}发布于 2014-07-02 22:24:23
关闭结果集、语句或连接等数据库资源的正确位置是try-catch语句的finally块。因为,JVM在任何情况下都会访问这个块。
以下用法是安全的:
ResultSet rs = null;
Statement stmt = null;
Connection conn = null;
try {
conn = SomeDBUtility.getConnection();
stmt = conn.createStatement();
rs = stmt.executeQuery("<Your SQL string>");
} catch (SQLException e) {
// handle the exception
} finally {
rs.close();
stmt.close();
conn.close();
}https://stackoverflow.com/questions/24533419
复制相似问题