Spring框架学习[JdbcTemplate封装Jdbc](六)
ert.notNull(action, "Callback object must not be null"); if (logger.isDebugEnabled()) { String sql = getSql(psc); logger.debug("Executing prepared SQL statement" + (sql != null " [" + sql + "]" : "")); } //获取数据库连接 Connection con = DataSourceUtils.getConnection(getDataSource()); PreparedStatement ps = null; try { Connection conToUse = con; //如果JdbcTemplate指定了jdbc本地提取器,则将获取到的数据库连接转换 //为本地数据库连接 if (this.nativeJdbcExtractor != null && this.nativeJdbcExtractor.isNativeConnectionNecessaryForNativePreparedStatements()) { conToUse = this.nativeJdbcExtractor.getNativeConnection(con); } //根据数据库连接和sql语句创建PreparedStatement ps = psc.createPreparedStatement(conToUse); applyStatementSettings(ps); PreparedStatement psToUse = ps; //如果JdbcTemplate指定了jdbc本地提取器,则将PreparedStatement转换 //为本地PreparedStatement if (this.nativeJdbcExtractor != null) { psToUse = this.nativeJdbcExtractor.getNativePreparedStatement(ps); } //调用回调处理器,执行相应操作 T result = action.doInPreparedStatement(psToUse); handleWarnings(ps); return result; } catch (SQLException ex) { //关闭资源,释放连接 if (psc instanceof ParameterDisposer) { ((ParameterDisposer) psc).cleanupParameters(); } String sql = getSql(psc); psc = null; JdbcUtils.closeStatement(ps); ps = null; DataSourceUtils.releaseConnection(con, getDataSource()); con = null; //将jdbc相关异常封装转换为Spring异常向调用者抛出 throw getExceptionTranslator().translate("PreparedStatementCallback", sql, ex); } finally { //清除PreparedStatement的参数 if (psc instanceof ParameterDisposer) { ((ParameterDisposer) psc).cleanupParameters(); } //关闭PreparedStatement JdbcUtils.closeStatement(ps); //释放数据库连接 DataSourceUtils.releaseConnection(con, getDataSource()); } }