我应该首先关闭哪个,PreparedStatement还是Connection?

在JDBC中使用PreparedStatement时,我应该首先关闭PreparedStatement还是首先关闭Connection ? 我刚看到一个代码示例,其中Connection首先被关闭,但在我看来首先关闭PreparedStatement更合乎逻辑。

是否有标准的,可接受的方式来做到这一点? 有关系吗? 关闭Connection还会导致PreparedStatement关闭,因为PreparedStatementConnection对象直接相关吗?

该声明。 我希望你关闭(按顺序)

  1. 结果集
  2. 该声明
  3. 连接

(并检查沿途的空值!)

即以与开启顺序相反的顺序关闭。

如果您使用Spring JdbcTemplate (或类似),那么将为您照顾。 或者,您可以使用Apache Commons DbUtils和DbUtils.close()DbUtils.closeQuietly()

应该完成以下程序(按顺序)

  • ResultSet
  • PreparedStatement
  • Connection

此外,建议关闭finally close中的所有JDBC相关对象以保证闭包。

 //Do the following when dealing with JDBC. This is how I've implemented my JDBC transactions through DAO.... Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { conn = .... ps = conn.prepareStatement(...); //Populate PreparedStatement rs = ps.executeQuery(); } catch (/*All relevant exceptions such as SQLException*/Exception e) { logger.error("Damn, stupid exception: " , e); } finally { if (rs != null) { try { rs.close(); rs = null; } catch (SQLException e) { logger.error(e.getMessage(), e.fillInStackTrace()); } } if (ps != null) { try { ps.close(); ps = null; } catch (SQLException e) { logger.error(e.getMessage(), e.fillInStackTrace()); } } try { if (conn!= null && !conn.isClosed()){ if (!conn.getAutoCommit()) { conn.commit(); conn.setAutoCommit(true); } conn.close(); conn= null; } } catch (SQLException sqle) { logger.error(sqle.getMessage(), sqle.fillInStackTrace()); } } 

您可以看到我已检查我的对象是否为空并且是否为连接,请首先检查连接是否未自动更新。 许多人未能检查它并意识到事务尚未提交给DB。