从一个 class 方法获取所有值到另一个 class 方法

get all values from one class to anothed class method

我有一个 class IntegrationWithDB,我必须在其中使用方法 getConnection() 和 selectFromDB()。

在另一个class test中我有方法displayList()在这个方法中我写了下面的代码

public class test {


     IntegrationWithDbClass qaz = new IntegrationWithDbClass();

    public  void displayList ( ) {


       qaz.getConnection();
       qaz.selectFromDB();


       for(int i = 0; i< 5; i++){
        System.out.println(" "+qaz.getId()); 
         System.out.println(" "+qaz.getNam());
       }

          }

当我在 main 方法中初始化 displayList() 方法时,它显示以下结果

5
red

如何获得所有五个值?

我假设您当前将这些属性存储在 int/string 变量中。在循环的每次迭代中,您都在覆盖这些值。您需要做的是将它们存储在像 ArrayList 这样的集合中,并在每次迭代中将 add() 添加到该集合中。

首先,您必须创建通常称为 Entity class 的内容。这是代表数据库中 单行 的 class。理想情况下,这应该与与数据库连接交互的代码分开。

所以第一步,创建一个名为 Contact 的 class,并在其中放入您拥有的 4 个字段,idnameparentlevel,以及相应的 getter 方法。如果您不希望这些通过您的程序改变,使它们不可变,那么确保一致性是好的做法。所以像:

public class Contact {

   private final int id;
   private final String name;
   private final String parent;
   private final String level;

   public Contact(String id, String name, String parent, String level) {
     this.id = id;
     this.name = name;
     this.parent = parent;
     this.level = level;
   }

   public int getId() {
     return id;
   }

   //... put the rest of the getter methods
}

然后在你的 IntegrationWithDB class 中(我会把它重命名为更有意义的东西,比如 ContactRepository)你可以改变你必须的方法:

public List<Contact> getContacts() {
   // ... your database connection and query code here

   this.rs = this.stmt.executeQuery(query);

   List<Contact> contacts = new LinkedList<Contact>();

   while (rs.next()) {

      int id = rs.getInt("node_id");                               
      String name = rs.getString("node_name");
      String parent = rs.getString("node_parent");
      String level = setLvl(rs.getInt("level"));

      contacts.add(new Contact(id, name, parent, level));
   }

   //... the rest of your database handling code, don't forget to close the connection

   return contacts;
 }

然后从 displayList() 你只需要调用 getContacts() 它会给你一个 Contact 对象的列表来迭代。