使用spring的jdbcTemplate用PreparedStatement执行sql的时候,怎么打印最终执行的sql。 10
修改log4j的日志级别是解决不了,请大神帮帮忙。 展开
这个问题简单。首先你自己创建一个MyJdbcTemplate。继承JdbcTemplate,然后重载下面的两个方法:
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ParameterDisposer;
import org.springframework.jdbc.core.PreparedStatementCallback;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.util.Assert;
public <T> T query(PreparedStatementCreator psc,
final PreparedStatementSetter pss, final ResultSetExtractor<T> rse)
throws DataAccessException {
Assert.notNull(rse, "ResultSetExtractor must not be null");
logger.debug("Executing prepared SQL query");
return execute(psc, new PreparedStatementCallback<T>() {
public T doInPreparedStatement(PreparedStatement ps)
throws SQLException {
ResultSet rs = null;
try {
if (pss != null) {
pss.setValues(ps);
}
if (logger.isDebugEnabled()) {
logger.debug(ps.toString());
}
rs = ps.executeQuery();
ResultSet rsToUse = rs;
if (getNativeJdbcExtractor() != null) {
rsToUse = getNativeJdbcExtractor().getNativeResultSet(rs);
}
return rse.extractData(rsToUse);
} finally {
JdbcUtils.closeResultSet(rs);
if (pss instanceof ParameterDisposer) {
((ParameterDisposer) pss).cleanupParameters();
}
}
}
});
}
protected int update(final PreparedStatementCreator psc,
final PreparedStatementSetter pss) throws DataAccessException {
logger.debug("Executing prepared SQL update");
return execute(psc, new PreparedStatementCallback<Integer>() {
public Integer doInPreparedStatement(PreparedStatement ps)
throws SQLException {
try {
if (pss != null) {
pss.setValues(ps);
}
if (logger.isDebugEnabled()) {
logger.debug(ps);
}
int rows = ps.executeUpdate();
if (logger.isDebugEnabled()) {
logger.debug("SQL update affected " + rows + " rows");
}
return rows;
} finally {
if (pss instanceof ParameterDisposer) {
((ParameterDisposer) pss).cleanupParameters();
}
}
}
});
}
然后就会打印最终执行的sql。
如果用spring ioc ,要改配置文件,比如:
<bean id="jdbcTemplate" class="MyJdbcTemplate" p:dataSource-ref="dataSource-mysql" />