1. 程式人生 > >如何動態的獲取資料庫裡面的欄位以…

如何動態的獲取資料庫裡面的欄位以…

private String getResult(String sql){
  
  Connection conn=null;
  ResultSet rs=null;
  conn= DBConnection.getConnection(Constants.DATABASE_PATH_STYLE);

  PreparedStatement selectPS = conn.prepareStatement(sql);
  try {
    rs = selectPS.executeQuery();
  } catch (SQLException e1) {
   // TODO Auto-generated catch block
   e1.printStackTrace();
  }
  ArrayList lstThemes=new ArrayList();
  try {
   if(rs!=null){
    int colCount=rs.getMetaData().getColumnCount();
    while(rs.next()){
     HashMap hm=new HashMap();
     for(int i=1;i<=rs.getMetaData().getColumnCount();i++){
      String colName=rs.getMetaData().getColumnName(i);
      if("getValidColumnIndex".equals(colName))
      {
       continue;
      }
      hm.put(colName,rs.getString(colName));
     }
     lstThemes.add(hm);
    }
   }
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }finally{
   DBConnection.closeConnection(conn);
  }
  JSONArray json = JSONArray.fromObject(lstThemes);
  return json.toString();
 }