Spring框架学习[JdbcTemplate封装Jdbc](八)

2014-11-24 03:05:49 · 作者: · 浏览: 10
{ ((ParameterDisposer) pss).cleanupParameters(); } } } }); }

(3). PreparedStatement的更新方法:

[java] view plaincopyprint // PreparedStatement更新方法,第二个参数PreparedStatementSetter为向//PreparedStatement设置参数的类 protected int update(final PreparedStatementCreator psc, final PreparedStatementSetter pss) throws DataAccessException { logger.debug("Executing prepared SQL update"); //调用PreparedStatement的execute方法,第二个参数为实现了//PreparedStatementCallback接口的匿名内部类,由PreparedStatement的 //execute方法回调 return execute(psc, new PreparedStatementCallback () { //真正执行jdbc操作的方法 public Integer doInPreparedStatement(PreparedStatement ps) throws SQLException { try { //为PreparedStatement设置参数值 if (pss != null) { pss.setValues(ps); } //PreparedStatement调用jdbc的更新操作,返回受影响的行数 int rows = ps.executeUpdate(); if (logger.isDebugEnabled()) { logger.debug("SQL update affected " + rows + " rows"); } return rows; } finally { //清除PreparedStatement参数 if (pss instanceof ParameterDisposer) { ((ParameterDisposer) pss).cleanupParameters(); } } } }); }

通过对PreparedStatement相关处理方法的源码分析,我们可以看到PreparedStatement和Statement的处理流程基本是相同的,不同之处在于PreparedStatement需要处理设置参数值的操作。

5.JdbcTemplate处理CallableStatement的相关方法实现:

(1).处理CallableStatement的execute方法:

[java] view plaincopyprint //CallableStatement处理给定字符串的 public T execute(String callString, CallableStatementCallback action) throws DataAccessException { //将字符串封装为SimpleCallableStatementCreator类,调用execute方法处//理CallableStatement return execute(new SimpleCallableStatementCreator(callString), action); } //CallableStatement的execute方法,第一个参数CallableStatementCreator是封装调用字//符串的类,封装调用数据库存储过程的语句 public T execute(CallableStatementCreator csc, CallableStatementCallback action) throws DataAccessException { Assert.notNull(csc, "CallableStatementCreator must not be null"); Assert.notNull(action, "Callback object must not be null"); if (logger.isDebugEnabled()) { String sql = getSql(csc); logger.debug("Calling stored procedure" + (sql != null " [" + sql + "]" : "")); } //根据数据源获取数据库连接 Connection con = DataSourceUtils.getConnection(getDataSource()); CallableStatement cs = null; try { Connection conToUse = con; //如果JdbcTemplate指定了本地jdbc提取器,则将获取到的数据库连接转换为 //本地数据库连接 if (this.nativeJdbcExtractor != null) { conToUse = t