数据库里取出来结果,按照树来排列。 其实就是数据结构中二叉树的先序遍历

本文介绍了一种使用递归方法从数据库中获取树状结构数据的方法,并提供了完整的Java实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

数据库里取出来结果,按照树来排列。   其实就是数据结构中的  先序遍历, 其实树并不陌生,关键试如何

保持思路去设计。在这里我通过递归方法得到树型结构的数据记录。另外jdbc连接数据库也忘记的厉害了,汗一个

。也许是数据源呀 持久工具之类的东西用的太久了 ,最原始的东西倒忘记了 。不过权作为一次复习了,反朴归

真 温故知新。。

数据库设计:

CREATE TABLE `city` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(20) default NULL,
  `parent` int(11) default NULL,
  `level` int(11) default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

package com.test.TestClass;

public class CityBean {

    
private int id;
    
private String name;
    
private int parent;
    
private int level;
    
private String displayName;
    
    
public String getDisplayName() {
        
return displayName;
    }

    
public void setDisplayName(String displayName) {
        
this.displayName = displayName;
    }

    
public int getId() {
        
return id;
    }

    
public void setId(int id) {
        
this.id = id;
    }

    
public int getLevel() {
        
return level;
    }

    
public void setLevel(int level) {
        
this.level = level;
    }

    
public String getName() {
        
return name;
    }

    
public void setName(String name) {
        
this.name = name;
    }

    
public int getParent() {
        
return parent;
    }

    
public void setParent(int parent) {
        
this.parent = parent;
    }

    
}

 

 

package com.test.TestClass;

import java.io.IOException;
import java.sql.*;
import java.util.*;

public class CityTree {

    
public static final  String url = "jdbc:mysql://localhost:3008/haha";

    
public static final  String username = "root";

    
public static final  String password = "root";
    
    
public static final String table = "city";
    
    ArrayList all 
= new ArrayList();
    
    Connection con 
= null;
    
    
//获得数据库连接
    private  Connection getMysqlCon (){
        
try {
            Class.forName(
"com.mysql.jdbc.Driver").newInstance();
        }
 catch (InstantiationException e) {
            
// TODO Auto-generated catch block
            e.printStackTrace();
        }
 catch (IllegalAccessException e) {
            
// TODO Auto-generated catch block
            e.printStackTrace();
        }
 catch (ClassNotFoundException e) {
            
// TODO Auto-generated catch block
            e.printStackTrace();
        }


        
try {
            con 
= DriverManager.getConnection(url, username,password);
        }
 catch (SQLException e) {
            
// TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println(con);
        
return con;
    }


    
// 是否有子级
    public boolean havaChild(CityBean aRoot) throws SQLException{
        
int count = 0;
        Connection con 
= this.getMysqlCon();
        Statement stmt 
= con.createStatement();
        String query 
= "select * from " + table + " where parent =" + aRoot.getId();
        ResultSet rs 
= stmt.executeQuery(query);
        
while (rs.next()) {
            count
++;
        }

        rs.close();
        stmt.close();
        con.close();
        
        
if(count>0){
            
return true;
        }

        
return false;
    }

    
    
// 获得某个节点的所有下级
    public ArrayList getAllChilds(CityBean aRoot) throws SQLException{
        ArrayList
<CityBean> allChilds = new ArrayList<CityBean>();
        Connection con 
= this.getMysqlCon();
        Statement stmt 
= con.createStatement();
        String query 
= "select * from " + table + " where parent =" + aRoot.getId();
        ResultSet rs 
= stmt.executeQuery(query);
        ResultSetMetaData rsmd 
= rs.getMetaData();
        
int columnCount = rsmd.getColumnCount();
        
while (rs.next()) {
            CityBean city 
= new CityBean();
            
for (int i = 1; i <= columnCount; i++{
                city.setId(rs.getInt(
1));
                city.setName(rs.getString(
2));
                city.setParent(rs.getInt(
3));
                city.setLevel(rs.getInt(
4));
                
                
// display 为显示在页面的字符 由 ***** 和名字组成,以显示他们的级别
                String displayName = "";
                String temp 
= "*****";
                
for(int j=0;j<rs.getInt(4);j++){
                    displayName 
= displayName + temp;
                }

                city.setDisplayName(displayName 
+ rs.getString(2));
            }

            allChilds.add(city);
        }

        rs.close();
        stmt.close();
        con.close();
        
return  allChilds;
    }

    
    
// 第归遍历函数
    public void getTreeList(CityBean aRoot) throws SQLException{
        
if(havaChild(aRoot)){
            all.add(aRoot);
            ArrayList temp 
= this.getAllChilds(aRoot);
            
for(int i=0;i<temp.size();i++){
                getTreeList((CityBean)temp.get(i));
            }

        }

        
else{
            all.add(aRoot);
        }

    }

    
    
// 测试类。根据根(id = 1 )得到他的所有子节点,先把要查的父亲节点实例化,也可以根据sql得到一个你要的父节点
    
// 这里我设置死了。
    public void getTheTreeList() throws SQLException{
        CityBean city 
= new CityBean();
        
        
//如要得到zhejiang 以下的:
        city.setId(1);
        city.setParent(
0);
        city.setName(
"zhejiang");
        city.setLevel(
1);
        city.setDisplayName(
"zhejiang");
        
         
//如要得到hangzhou 以下的:
//        city.setId(2);
//        city.setParent(1);
//        city.setName("hangzhou");
//        city.setLevel(2);
//        city.setDisplayName("hangzhou");
        this.getTreeList(city);
    }

    
    
public static void main(String[] args) throws IOException, SQLException {
        CityTree obj 
= new CityTree();
        
        
// 测试连接数据库
        
// obj.getMysqlCon();
        
        obj.getTheTreeList();
        System.out.println(obj.all.size());
        
for(int i = 0;i<obj.all.size();i++){
            CityBean bean 
= new CityBean();
            bean 
= (CityBean) obj.all.get(i);
            System.out.println(bean.getDisplayName());
        }

        
    }

}

 

其实我觉得这个是比较普遍的问题,实用性也比较广,不知道贴出来的对大家有帮助没 ,欢迎探讨共勉。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值