import org.slf4j.LoggerFactory;
import com.alibaba.druid.pool.DruidDataSource;
public class JDBCUtils {
private final static Logger log = LoggerFactory.getLogger(JDBCUtils.class);
/**
- 定义数据源
*/
private static DataSource ds;
/**
- 定义数据库连接配置
*/
static {
try {
/**
- 加载配置文件
*/
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(“org.postgresql.Driver”);
dataSource.setUrl(“jdbc:postgresql://127.0.0.1:5432/test”);
dataSource.setUsername(“postgres”);
dataSource.setPassword(“123456”);
ds = dataSource;
} catch (Exception e) {
log.error(“create connection pool error,errorMessage:{}”, e);
}
}
/**
-
获取数据源
-
@return 返回数据源
*/
public static DataSource getDataSource(){
return ds;
}
/**
-
获取连接对象
-
@return 返回连接对象
-
@throws SQLException 抛出的编译异常
*/
public static Connection getConn() throws SQLException {
return ds.getConnection();
}
/**
-
关闭连接
-
@param stmt sql执行对象
-
@param conn 数据库连接对象
*/
public static void close(Statement stmt, Connection conn){
if(stmt != null){
try {
stmt.close();
} catch (SQLException e) {
log.error(“close error,errorMessage:{}”, e);
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
log.error(“close error,errorMessage:{}”, e);
}
}
}
/**
-
关闭资源的重载方法
-
@param rs 处理结果集的对象
-
@param stmt 执行sql语句的对象
-
@param conn 连接数据库的对象
*/
public static void close(ResultSet rs, Statement stmt, Connection conn){
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
log.error(“close error,errorMessage:{}”, e);
}
}
if(stmt != null){
try {
stmt.close();
} catch (SQLException e) {
log.error(“close error,errorMessage:{}”, e);
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
log.error(“close error,errorMessage:{}”, e);
}
}
}
}
二、jdbcTemplate.queryForList源码初探
public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
public JdbcTemplate(DataSource dataSource) {
setDataSource(dataSource);
afterPropertiesSet();
}
@Override
public List<Map<String, Object>> queryForList(String sql) throws DataAccessException {
return query(sql, getColumnMapRowMapper());
}
@Ov