【发布时间】:2010-11-16 14:56:35
【问题描述】:
我的 JDBC 连接代码类似于 Java JDBC 教程中的以下代码:
public static void viewTable(Connection con) throws SQLException {
Statement stmt = null;
String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from " + dbName + ".COFFEES";
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String coffeeName = rs.getString("COF_NAME");
int supplierID = rs.getInt("SUP_ID");
float price = rs.getFloat("PRICE");
int sales = rs.getInt("SALES");
int total = rs.getInt("TOTAL");
System.out.println(coffeeName + "\t" + supplierID + "\t" + price + "\t" + sales + "\t" + total);
}
} catch (SQLException e ) {
JDBCTutorialUtilities.printSQLException(e);
} finally {
stmt.close();
}
}
我对这种处理连接方式的问题是它关闭了finally 块中的语句,并且该方法抛出了任何可能发生的 SQLException。我不想这样做,因为我希望在这个类中处理任何问题。但是,我确实希望在 finally 块中调用 Statement#close(),以便它始终关闭。
现在我将此代码放在一个单独的方法中,该方法返回一个HashMap 的字段,该字段返回到该异常在类中处理。还有其他更好的方法来处理这个问题吗?
编辑:close() SQLException 是我所关心的。如果可能的话,我想在方法中处理它。我可以在 finally 中写一个 try/catch,但这似乎很尴尬。
【问题讨论】:
-
这很模棱两可。
My problem with this way of handling to connection is that it closes the statement in the finally block and the method throws any SQLException that may occur. I don't want to do that, because I want any problems handled within this class. However, I do want that Statement#close() call in the finally block so that it is always closed. -
该代码捕获所有 SQL 异常,除了(可能)从
.close()调用返回的一个异常(如果它甚至可以抛出一个)。我认为该代码已经非常接近您想要的,但是您的问题并不是很清楚。
标签: java jdbc sqlexception