前言
SpringBoot项目整合数据库连接池后,默认使用Hikari连接池
配置
使用连接池实现查询
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| @Repository public class DefaultGoodsDao implements GoodsDao {
@Autowired DataSource dataSource;
@Override public List<Map<String, Object>> findGoods() { List<Map<String, Object>> list = new ArrayList<>(); try { Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("SELECT * FROM tb_goods"); while(resultSet.next()) { int id = resultSet.getInt("id"); String name = resultSet.getString("name"); String remark = resultSet.getString("remark"); Time createdTime = resultSet.getTime("createdTime"); Map<String, Object> map = new HashMap<>(); map.put("id", id); map.put("name", name); map.put("remark", remark); map.put("createdTime", createdTime); list.add(map); } resultSet.close(); statement.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } return list; }
}
|
进行简单的封装
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| @Repository public class DefaultGoodsDao implements GoodsDao{ @Autowired private DataSource dataSource; public List<Map<String,Object>> findGoods(){ Connection conn=null; Statement stmt=null; ResultSet rs=null; String sql="select id,name,remark note,createdTime from tb_goods"; try { conn=dataSource.getConnection(); stmt=conn.createStatement(); rs=stmt.executeQuery(sql); List<Map<String,Object>> list=new ArrayList<>(); while(rs.next()){ list.add( rowMap(rs)); } return list; }catch (SQLException e){ e.printStackTrace(); throw new RuntimeException(e); }finally{ close(rs,stmt,conn); } } private Map<String,Object> rowMap(ResultSet rs)throws SQLException{ Map<String,Object> rowMap=new HashMap<>(); ResultSetMetaData rsmd=rs.getMetaData(); int columnCount=rsmd.getColumnCount(); for(int i=0;i<columnCount;i++){ rowMap.put(rsmd.getColumnLabel(i+1),rs.getObject(rsmd.getColumnLabel(i+1))); } return rowMap; } private void close(ResultSet rs,Statement stmt,Connection conn){ if(rs!=null)try{rs.close();}catch(Exception e){e.printStackTrace();} if(stmt!=null)try{stmt.close();}catch(Exception e){e.printStackTrace();} if(conn!=null)try{conn.close();}catch(Exception e){e.printStackTrace();} } }
|
完成