为什么下面finally里面的东西有问题呢
package Student;import java.sql.*;public class Student {

public static void main(String[] args){
Connection con=null;
PreparedStatement pStatement=null;
ResultSet rs=null;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}catch(ClassNotFoundException se){
System.out.println("找不到数据库驱动");
}
try{
con=DriverManager.getConnection("jdbc:odbc:Temp");
String sql="select * from student";
pStatement=con.prepareStatement(sql);
rs=pStatement.executeQuery();
while(rs.next()){
System.out.println(rs.getInt(1));
System.out.println(rs.getString(2));
}
}catch(SQLException se){
se.printStackTrace();
}finally{
rs.close();
pStatement.close();
con.close();
}
}
}

解决方案 »

  1.   

    因为在 close 的时候会抛出 SQLException,因为可能在关闭时数据库连接发生异常,需要捕获一下就可以了。} finally {
        if(rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }    if(....) // 照上面这样关闭另外两个。
    }
      

  2.   

    如果想偷懒的话,可以写个工具类:import java.sql.Connection;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;public class JdbcUtil {    public static void close(Connection con, Statement stat, ResultSet rs)  {
            close(rs);
            close(stat);
            close(con);
        }    public static void close(Connection con, Statement stat)  {        
            close(con, stat, null);
        }    public static void close(Connection con, ResultSet rs)  {        
            close(con, null, rs);
        }    public static void close(Connection con)  {
            if(con != null) {
                try {
                    con.close();
                } catch(SQLException e) {
                    e.printStackTrace();
                }
            }        
        }    public static void close(Statement stat)  {
            if(stat != null) {
                try {
                    stat.close();
                }catch(SQLException e) {
                    e.printStackTrace();
                }
            }
        }    public static void close(ResultSet rs)  {
            if(rs != null) {
                try {
                    rs.close();
                }catch(SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }finally 中改成:} finally {
        JdbcUtil.close(con, pStatement, rs);
    }