从数据库创建一个树

时间:2018-02-22 12:16:25

标签: java sql jdbc

我有一个SQL表,其结构如下:

 name      last-name
 -------------------
 maria     moh adam
 rami      moh adam
 sabi      ali adam
 mary      joh ali

如何创建以下表示的树:

                    adam
                    /  \
                 moh    ali
                 /      /  \
             maria    sabi  joh
                             |
                             mary

我尝试了这两种不同的方法......但它不起作用:



private void addniv1(Node root,Node tree) {
		 int cols =3;
		Node niv=null;
		 Node niv1=null;
				 
			TableModel model = table.getModel();
			int row = model.getRowCount();
			Object[] values = new Object[ row ];
			for ( int rows = 1; rows < row; rows++ ) 
			 {
				values[ rows ] = model.getValueAt( rows, 3 );
				String pere[]= ((String) values[rows]).split(" ");
				String gr_fath=pere[2];
				String father=pere[0];
				values[ rows ] = model.getValueAt( rows, 0 );
				String fils=(String) values[ rows ];
				if(root.getData().equals(gr_fath)) {
					 niv=new Node(father);
					 root.addChild(niv); 
					 AddChilds(root,niv);
					  } }
   //*********************************************
   private void AddChilds(Node tree, Node child) {
	String str=child.getData()+" "+"bn"+" "+tree.getData();
	String SQL="select distinct * from Base1 where father='"+str+"' ";
		        ResultSet rs;
				try {
					rs = statement.executeQuery(SQL);
				while(rs.next())
				 {
				   Node child3= new Node(rs.getString("prenom"));
				   child3.setParent(child);
				    child.addChild(child3);
				    AddChilds(child,child3);
				        }
				      
				} catch (SQLException e) {
					
					e.printStackTrace();
				}
		      
				
&#13;
&#13;
&#13;

我的问题是: - 当我有相同的姓氏时......代码重复节点父子  这个例子:

&#13;
&#13;
                           adam
                    /        |            \
                 moh        moh          ali
                 /\         /  \         /  \
             maria rami   rami maria   sabi  joh
                                              |
                                             mary
&#13;
&#13;
&#13;

0 个答案:

没有答案