数据库查询返回List

 

protected List> doQuery(String sql) throws Exception {
  logger.debug("method:doQuery----START");
  List> list = new ArrayList>();

  // 关闭连接flag
  boolean colseFlag = false;

  // 打开DB链接
  if (this.connection == null) {
   this.connection = this.getDbConnection();
   colseFlag = true;
  }
  PreparedStatement preStat = null;

  if (this.connection != null) {
   try {
    preStat = this.connection.prepareStatement(sql);
    // 查询一个结果集
    ResultSet rs = null;
    Map map = null;
    logger.debug("SQL:" + sql);
    rs = preStat.executeQuery();

    // 生成ResultSetMetaData
    ResultSetMetaData rsMeta = preStat.getMetaData();
    while (rs.next()) {
     map = this.Result2Map(rs, rsMeta);
     // 追加到list中
     list.add(map);
    }
   } catch (Exception e) {
    // 记录错误信息
    logger.error(e.getMessage(), e);
    throw e;
   } finally {
    if (preStat != null) {
     try {
      preStat.close();
     } catch (SQLException e) {
      logger.error(e.getMessage(), e);
      throw e;
     } finally {
      preStat = null;
     }
    }
    // 关闭数据库连接
    if (colseFlag) {
     this.closeDbConnection(this.connection);
    }
   }
  } else {
   throw new Exception("DB链接未取到.");
  }
  logger.debug("method:doQuery----END");
  return list;
 }

 

private Map Result2Map(ResultSet rs, ResultSetMetaData meta) throws SQLException {
  Map map = new HashMap();
  for (int i = 1; i <= meta.getColumnCount(); i++) {
   map.put(meta.getColumnName(i), rs.getObject(meta.getColumnName(i)));
  }
  return map;
 }

你可能感兴趣的:(数据库查询返回List)