![](/img/trans.png)
[英]java.lang.ClassCastException: com.mysql.jdbc.JDBC4ResultSet cannot be cast to com.mysql.jdbc.ResultSet
[英]com.mysql.jdbc.JDBC4ResultSet cannot be cast to java.io.Closeable
尝试关闭连接时出现问题(我的程序可以运行,但是最后出现错误)
这是问题所在的部分(与我将连接投射到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)
如果删除强制类型转换方法,则会出现语法错误。 有什么建议么 ? 进口
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
}
com.mysql.jdbc.JDBC4ResultSet
不能com.mysql.jdbc.JDBC4ResultSet
为java.io.Closeable
因为它也不实现其Closable
接口。
如果将close方法更改为接受java.lang.AutoCloseable
并强制转换为该类型而不是java.io.Closable
则可能会起作用。
您的解决方案虽然有效,但并不是最佳选择,我建议您使用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
有关详细信息,请参见教程try-with-resources语句 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.