因为之前有一模块需要用到栏目下的所有子节点,注意:这里是说的所有栏目下的叶子节点。为此写了个类,同大家分享,希望可以帮到也遇到了这类问题的朋友
因为自己平时是个大条的人,写好的文件也不知道归档,所以贴出来便于以后的查找
package com;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.HashMap;
/**
* @Time 2011-08-17
* @author XMY
* 传入任意级别的节点ID,返回该节点下的所有最底级节点ID 并用,链接
*/
public class GetColidStr {
static String sql;
static Connection conn;
static PreparedStatement ps;
static ArrayList list;
static String selectsql ="select COLID,FATHERID from sy_column where fatherid in (";
/**
* 获得最底层ID的字符串并用,链接
* @param colid 节点ID
* @return String
* @throws Exception DB
*/
public static String getcolid(Connection conn,String colid) throws Exception {
String returnStr = "";
//conn creat 数据库自己创建,下面已经进行了数据库的关闭
//conn end
int i = 0;
while(true) {
i++;
sql = selectsql+colid +")";
ps=conn.prepareStatement(sql);
list=getList(ps.executeQuery());
ps.close();
if(list.size()>0){
if(colid.indexOf(",")>0) {//从0位开始查,判断colid是否存在多个值
} else {
colid = "";
}
String tt = "";
String tt1 = "";
for(int j=0;j<list.size();j++) {
colid += ((HashMap)list.get(j)).get("COLID").toString()+",";
if(tt.equals("")) {
tt = ((HashMap)list.get(j)).get("FATHERID").toString();
tt1 += ((HashMap)list.get(j)).get("COLID").toString()+",";
} else {
if(tt.equals(((HashMap)list.get(j)).get("FATHERID").toString())) {
tt1 += ((HashMap)list.get(j)).get("COLID").toString()+",";
} else {
if(j==list.size()-1) {
tt1 +="&"+((HashMap)list.get(j)).get("FATHERID").toString()+"fenge";
} else {
tt1 +="&"+((HashMap)list.get(j-1)).get("FATHERID").toString()+"fenge";
}
}
}
}
if(colid.length()>1){
colid = colid.substring(0,colid.length()-1);
}
if(!tt1.equals("")) {
if(tt1.indexOf("fenge")!=-1){
String[] tt2 = tt1.split("fenge");
for(int k=0;k<tt2.length;k++) {
colid = colid.replaceAll(tt2[k].split("&")[1]+",", tt2[k].split("&")[0]);
}
}
}
} else {
returnStr = colid ;
//System.out.println("一共查询了>>" + i +"次");
//System.out.println("所获得的最底层ID字符串为>>>"+returnStr);
if(ps!=null){
ps.close();
}
conn.close();
break;
}
}
return returnStr;
}
/**
* 讲 rs 内数据进行 list 化封装
* @param rs 结果集对象
* @return ArrayList
* @throws Exception rs
*/
public static ArrayList getList(ResultSet rs) throws Exception {
ResultSetMetaData d = rs.getMetaData();
ArrayList list = new ArrayList();
int colCount = 1;
colCount = d.getColumnCount();
while (rs.next()) {
HashMap colMap = new HashMap();
for (int i = 1; i <= colCount; i++) {
colMap.put(d.getColumnName(i).toUpperCase(),(rs.getString(i) == null)?"":rs.getString(i));
}
list.add(colMap);
}
rs.close();
return list;
}
/**
* 程序主方法
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
String colidStr = "";
//传入任意节点的ID
colidStr = getcolid("110");
if(colidStr.indexOf(",")>0) {
System.out.println("不是最底节,处理后最底节点字符串为>>>" + colidStr);
} else {
System.out.println("已经是最底层节点>>>>"+colidStr);
}
}
}