0

我正在研究http://java.sun.com/docs/books/tutorial/uiswing/examples/components/GenealogyExampleProject/src/components/GenealogyExample.java的示例

我想以一种从表中提取数据的方式对其进行自定义(folder_id, folder_name, parent_id[foreign key to determine parent]。

这是我的代码

 public Person getGenealogyGraph() throws SQLException {
    Connection con=null;
    Statement st=null;
    ResultSet rs=null;

    String driver ="com.mysql.jdbc.Driver";
    String url="jdbc:mysql://localhost:3306/";
    String db="java";
    con=DriverManager.getConnection(url + db, "root", "");
    ArrayList list=new ArrayList();

    try {
        String sql="Select * from folder";
        st=con.createStatement();
        rs=st.executeQuery(sql);
        list.add("Current Folders");
        while(rs.next()) {
            String folderName = rs.getString("folder_name");
            list.add(folderName);
           // System.out.println(folderName);
            //Person a1 = new Person(folderName);

        }


    } catch (Exception e) {
        System.out.println(e);
    }
    rs.close();
    st.close();
    con.close();

       Object hierarchy[]=list.toArray();
        for(int i=1; i<hierarchy.length; i++) {
           Person a+i=new Person(hierarchy[i]);
        }

如果我将其硬编码为 Person a1 = new Person("Jack (great-granddaddy)"); ,它工作正常。但是,我想把它放在一个循环中,变量 i :-

Object hierarchy[]=list.toArray();
        for(int i=1; i<hierarchy.length; i++) {
           Person a+i=new Person(hierarchy[i]);
 }

如何将变量 i 和“a”组合在一起?在 PHP 中,我们通常将它们与“.”组合在一起。, 例如 "a".$i;

谢谢 :) 任何其他关于从数据库创建树的示例也非常感谢。提前致谢

4

1 回答 1

0

我不确定您要做什么。但是,如果您想为变量分配动态名称,则应将对象存储在关联数组(java.util.Map)中

Map<String,Person> map= new HashMap<String,Person>();
(...)
map.put("a"+i,new Person(hierarchy[i]));
于 2009-12-05T09:20:02.347 回答