rs = stmt.executeQuery(sql);
return rse.extractData(rs);
}
finally {
JdbcUtils.closeResultSet(rs);
}
}
@Override
public String getSql() {
return sql;
}
}
return execute(new QueryStatementCallback());
}
@Override
@Nullable
public <T> T execute(StatementCallback<T> action) throws DataAccessException {
Assert.notNull(action, "Callback object must not be null");
Connection con = DataSourceUtils.getConnection(obtainDataSource());
Statement stmt = null;
try {
stmt = con.createStatement();
applyStatementSettings(stmt);
T result = action.doInStatement(stmt);
handleWarnings(stmt);
return result;
}
catch (SQLException ex) {
// Release Connection early, to avoid potential connection pool deadlock
// in the case when the exception translator hasn't been initialized yet.
String sql = getSql(action);
JdbcUtils.closeStatement(stmt);
stmt = null;
DataSourceUtils.releaseConnection(con, getDataSource());
con = null;
throw translateException("StatementCallback", sql, ex);
}
finally {
JdbcUtils.closeStatement(stmt);
DataSourceUtils.releaseConnection(con, getDataSource());
}
}
...
}
public interface Statement extends Wrapper, AutoCloseable {
ResultSet executeQuery(String sql) throws SQLException;
...
}
public abstract class JdbcAccessor implements InitializingBean {
@Nullable
private DataSource dataSource;
public void setDataSource(@Nullable DataSource dataSource) {
this.dataSource = dataSource;
}
}
```
三、更优雅的方式 -> 通过配置类方式实现
---------------------
### 1、application.yml
```
server:
port: 8080
spring:
application:
name: test
datasource:
sqlserver:
jdbc-url: jdbc:sqlserver://127.0.0.1:1433;DatabaseName=test
driverClassName: com.microsoft.sqlserver.jdbc.SQLServerDriver
username: sa
password: sa
postgres:
jdbc-url: jdbc:postgresql://127.0.0.1:5432/test
driverClassName: org.postgresql.Driver
username: postgres
password: 123456
```
### 2、配置类
```
package com.guor.config;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProp