【发布时间】:2018-10-24 06:01:32
【问题描述】:
我需要先从方法返回数据,然后调用连接,但是警告告诉我:“这个方法应该返回一个ResultSet类型的结果»,在方法的末尾添加一个返回,在关闭之后,但是如果您以警告仍然存在的方式编写它。也许我应该将其全部删除并以不同的方式使用封装?这是一种方法
public ResultSet doSQLQuery(String query) throws ClassNotFoundException{
Class.forName("com.mysql.jdbc.Driver");
String SQLQuery = query;
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try{
connection = DriverManager.getConnection(DB_URL,login,password);
statement = connection.prepareStatement(SQLQuery);
resultSet = statement.executeQuery();
return resultSet; //return from this place doesnt possible(?)
} catch (SQLException e) {
System.err.println("SQLException caught");
e.printStackTrace();
}finally {
if (resultSet != null)
try { resultSet.close(); }
catch (SQLException ignore) { }
if (statement != null)
try { statement.close(); }
catch (SQLException ignore) { }
if (connection != null)
try { connection.close(); }
catch (SQLException ignore) { }
}
}
upd:选择将返回类型更改为字符串作为解决方案
【问题讨论】:
-
好吧,如果你在第一个
catch结束,就没有return。 -
您正在返回一个关闭的 ResultSet。没有人可以使用它。 (另外,
Class.forName("com.mysql.jdbc.Driver");已经很多年不用了。) -
我应该将 return 添加到 finally 块中,但是在它的哪个位置,应该按什么顺序关闭连接并返回?
-
作为一个问题,出于理智的目的,我建议您创建静态帮助方法以优雅地关闭。
static void closeQuietly(ResultSet rs) { try { if (rs != null) rs.close(); } catch (Exception e) { } }这将使您的 finally 块变得简单:closeQuietly(resultSet); closeQuietly(statement); closeQuietly(connection);而不是三个 if/try/catch 语句。另一种选择是 try-with 附件,但有时这些附件效果不佳,例如使用 Prepared Statements。 -
@Compass 我从未见过 try-with-resources 语句无法处理 JDBC 对象。 try-with-resources 只是调用 Autocloseable 对象的
close()方法。
标签: java mysql try-catch database-connection