问题描述
Connection conn= DbUtil.getConnection();Statement stmt=null;System.out.println(conn+"&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");stmt=conn.createStatement();System.out.println(conn+"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");ResultSet rs = stmt.executeQuery("select * from exam order by exam_id");显示为:com.microsoft.jdbc.sqlserver.SQLServerConnection@161dfb5&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC]Object has been closed.at com.microsoft.jdbc.base.BaseExceptions.createException(Unknown Source)at com.microsoft.jdbc.base.BaseExceptions.getException(Unknown Source)at com.microsoft.jdbc.base.BaseConnection.validateClosedState(Unknown Source)at com.microsoft.jdbc.base.BaseConnection.createStatement(Unknown Source)at com.microsoft.jdbc.base.BaseConnection.createStatement(Unknown Source)at com.sdjzglxy.jwMis.dao.ExamDaoImpl.queryExams(ExamDaoImpl.java:87)at com.sdjzglxy.jwMis.jwMisFrame.JwMisFrame.createQueryPanel(JwMisFrame.java:421)at com.sdjzglxy.jwMis.jwMisFrame.JwMisFrame.<init>(JwMisFrame.java:96)at com.sdjzglxy.jwMis.jwMisFrame.JwMisFrame.main(JwMisFrame.java:719)我觉得问题是这段代码:stmt=conn.createStatement();因为我打印了conn它并不为null,但是执行stmt=conn.createStatement();却提示数据库已经关闭。我想问一下,究竟该如何解决。 问题补充:hudingchen 写道
解决方案
引用final public static void colse(ResultSet rs, Statement stmt, Connection conn)throws Exception {if (conn != null || !conn.isClosed()) { conn.close(); conn = null; } else { if (stmt != null) { stmt.close(); stmt = null; } else { if (rs != null) { rs.close(); rs = null; } }}}}我的DbUtil是这样写的,帮忙看一下是否正确!谢谢 这样写:if (rs != null){ rs.close(); rs = null;}if (stmt != null){ stmt.close(); stmt = null;}if (conn != null){ conn.close(); conn = null;}
解决方案二:
关闭的顺序不正确,应该先关闭resultset,然后是statement,最好才是connection,呵呵。
解决方案三:
final public static void colse(ResultSet rs, Statement stmt, Connection conn)throws Exception {if (rs != null) {rs.close();}if (stmt != null) {stmt.close();}if (conn != null || !conn.isClosed()) {conn.close();}}
解决方案四:
楼上的说的对。关闭顺序,必须严格按照rset, stmt, conn来。
解决方案五:
应该与conn,stmt,rs关闭顺序有关,应该先rs.close();然后stmt.close();最后conn.close();
解决方案六:
类DbUtil中的conn是static的,其他程序会修改的啊,你把close改成下面看看if (conn != null || !conn.isClosed()) {conn.close();conn = null;} else {if (stmt != null) {stmt.close();stmt = null;} else {if (rs != null) {rs.close();rs = null;}}}