package test; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; public class DBHelper { public static final String url = "jdbc:mysql://127.0.0.1/peixian"; public static final String name = "com.mysql.jdbc.Driver"; public static final String user = "root"; public static final String password = "root"; public Connection conn = null; public PreparedStatement pst = null; public DBHelper(String sql) { try { Class.forName(name);//指定连接类型 conn = DriverManager.getConnection(url,user,password);//获取连接 pst = conn.prepareStatement(sql);//准备执行语句 } catch (Exception e) { e.printStackTrace(); } } public void close() { try { this.conn.close(); this.pst.close(); } catch (SQLException e) { e.printStackTrace(); } } } //调用demo类================ package test; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.mysql.jdbc.StringUtils; public class Demo { static String sql = null; static DBHelper db1 = null; static ResultSet ret = null; public static void main(String[] args) { sql = "select *from xy_sys_menu";//SQL语句 db1 = new DBHelper(sql);//创建DBHelper对象 try { List<Map<String,Object>>list=new ArrayList<Map<String,Object>>(); ret = db1.pst.executeQuery();//执行语句,得到结果集 ResultSetMetaData md = ret.getMetaData(); //获得结果集结构信息,元数据 int columnCount = md.getColumnCount(); //获得列数 while (ret.next()) { Map<String,Object> rowData = new HashMap<String,Object>(); for (int i = 1; i <= columnCount; i++) { rowData.put(md.getColumnName(i), ret.getObject(i)); } list.add(rowData); } System.out.println("list============="+list); List<Map<String, Object>>listTree=getTreeList("MENU_NO","PMENU_NO","children",list); System.out.println("listTree===="+listTree); ret.close(); db1.close();//关闭连接 } catch (SQLException e) { e.printStackTrace(); } } //把带有父子机构的数据变成treelist形式 public static List<Map<String, Object>> getTreeList(String id,String pid,String children,List<Map<String, Object>>list) { //List<Map<String, Object>>listmap=new ArrayList<Map<String, Object>>(); //给list的每一项加一个子项 for(int i=0;i<list.size();i++) { list.get(i).put(children, new ArrayList<Map<String, Object>>()); } List<Map<String, Object>>treelist=new ArrayList<Map<String, Object>>(); for(Map<String, Object> outmap:list) { for(Map<String, Object> inmap:list) { String outid=outmap.get(id).toString(); String inpid=inmap.get(pid).toString(); if(outid.equals(inpid)) { List<Map<String, Object>>maplist=(ArrayList) outmap.get(children); maplist.add(inmap); } } String prid=outmap.get(pid).toString(); if(StringUtils.isNullOrEmpty(prid)) { treelist.add(outmap); } } return treelist; } }