最近项目中用到数据库,使用JDBC实现的,
发现1:ResultSet 依赖于Statement 依赖于 Connection 当我获得ResultSet后 后两个改变了,我的ResultSet也将遭到破坏,经常出现“结果集已经关闭”错误,网上查询解决方法有a为每个ResultSet独享Connection;b获得ResultSet后将其数据取出用容器包装。代码如下:
public List<Map<String,Object>> query(String sql){ List<Map<String,Object>> results=null; try { stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE); rs=stmt.executeQuery(sql); if(rs!=null){ results=new LinkedList<Map<String,Object>>(); ResultSetMetaData rsmd=rs.getMetaData(); //Get the count of columns int count=rsmd.getColumnCount(); //Iterate the ResultSet obtained while(rs.next()){ Map<String,Object> result=new HashMap<String, Object>();//row for(int i=1;i<=count;i++){ //Get the name of column by index, the index of the first is 1,then 2.... String name=rsmd.getColumnName(i); int type=rsmd.getColumnType(i); Object value=null; if(type==Types.DATE){ value=rs.getDate(name); }else{ value=rs.getString(name); if(value==null) value=""; } result.put(name, value); } results.add(result); } } } catch (SQLException e) { e.printStackTrace(); } return results; }
我选择的是基于第二个方法,鉴于不大想更改之前代码,我将ResultSet重新实现了,其中包装一个List<Map<String,Object>>。
发现2:使用上述方法后,发现第二个问题,ResultSet.next()不正常。实现如下:
public boolean next() throws SQLException { // need 修改 index += 1; if (index < resultList.size()){ return true; } return false; }
究其原因是:数据库在对一张空表进行 select *查询是 返回为0行;而对空表进行select max(。。。)进行查询时却是返回一行
这一行的内容是 NULL 。所以我在上面代码resultList.size() 进行判断会误导重新实现的结果集。
PS:不知道为什么数据库被设计成这样,我想知道原因,望大虾指点那。