com.mysql.jdbc.JDBC4ResultSet无法强制转换为java.io.Closeable

时间:2014-04-24 12:35:43

标签: java mysql jdbc

当我尝试关闭连接时出现问题(我的程序有效,但最后我收到错误)

这是问题所在的块(它与我将连接转换为Closeable的方式有关)

 private void close() {
    close((Closeable) resultSet);
    close((Closeable) statement);
    close((Closeable) connect);
  }
  private void close(Closeable c) {
    try {
      if (c != null) {
        c.close();
      }
    } catch (Exception e) {
    // don't throw now as it might leave following closables in undefined state
    }

这是错误:

Exception in thread "main" java.lang.ClassCastException: com.mysql.jdbc.JDBC4ResultSet cannot be cast to java.io.Closeable
    at de.vogella.mysql.first.DeVogellaMysqlFirst.close(DeVogellaMysqlFirst.java:105)
    at de.vogella.mysql.first.DeVogellaMysqlFirst.readDataBase(DeVogellaMysqlFirst.java:68)
    at de.vogella.mysql.first.test.main(test.java:8)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

如果我删除了cast方法,我会收到语法错误。 有什么建议 ? IMPORT

import java.lang.AutoCloseable;

正确版本:

private void close(AutoCloseable c) throws UnsupportedOperationException {
    try {
      if (c != null) {
        c.close();
      }
    } catch (Exception e) {
    // don't throw now as it might leave following closables in undefined state
    }

2 个答案:

答案 0 :(得分:4)

com.mysql.jdbc.JDBC4ResultSet无法转换为java.io.Closeable,因为它没有,也没有任何子类实现Closable接口。

如果您更改close方法以接受java.lang.AutoCloseable并转换为该类型而不是java.io.Closable,则可能会有效。

答案 1 :(得分:1)

您的解决方案虽然有效并非最佳,但我建议使用try-with-resources。这可确保所有AutoCloseable(和Closeable)对象以正确的顺序关闭,即使发生异常也是如此。额外的好处是你实际上不会吞下/忽略异常。

例如:

try (
    Connection con = DriverManager.getConnection(...);
    Statement stmt = con.createStatement();
    ResultSet rs = stmt.executeQuery(....)
) {
    // Process result set
}
// con, stmt and rs are guaranteed to have been closed here

有关详细信息,请参阅教程The try-with-resources Statement