【问题标题】:Reading Data From Database and storing in Array List object从数据库中读取数据并存储在数组列表对象中
【发布时间】:2020-07-26 18:25:14
【问题描述】:

您好,我想在 html 页面上显示我的数据库表的全部内容。我正在尝试首先从数据库中获取记录并存储在 ArrayList 但是当我在 html 页面上返回数组列表时,它只会重复显示最后一条记录我的数据库表的计数。 下面是代码:

public ArrayList<CustomerDTO> getAllCustomers() 
{
    ArrayList<CustomerDTO> customers = new ArrayList<CustomerDTO>();
    CustomerDTO customer = null;
    Connection c;
    try {
        c = openConnection();
        Statement statement = c.createStatement();
        String s = "SELECT * FROM customer";

        ResultSet rs = statement.executeQuery(s);
        int g =0;

        while (rs.next()) {

            customer.setId(rs.getInt("id"));
            customer.setName(rs.getString("name"));

            customer.setAddress(rs.getString("address"));
            customer.setPhone(rs.getString("phone"));
            customer.setEmail(rs.getString("email"));
            customer.setBountPoints(rs.getInt("bonuspoint"));
            customer.setTotalsale(rs.getInt("totalsale"));

            customers.add(customer);
        }

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

    return customers;
}

【问题讨论】:

    标签: java jdbc


    【解决方案1】:

    试试下面的代码

    public static ArrayList<Customer> getAllCustomer() throws ClassNotFoundException, SQLException {
        Connection conn=DBConnection.getDBConnection().getConnection();
        Statement stm;
        stm = conn.createStatement();
        String sql = "Select * From Customer";
        ResultSet rst;
        rst = stm.executeQuery(sql);
        ArrayList<Customer> customerList = new ArrayList<>();
        while (rst.next()) {
            Customer customer = new Customer(rst.getString("id"), rst.getString("name"), rst.getString("address"), rst.getDouble("salary"));
            customerList.add(customer);
        }
        return customerList;
    }
    

    这是我的模型类

    public class Customer {
    private String id;
    private String name;
    private String salary;
    private String address;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSalary() {
        return salary;
    }
    public void setSalary(String salary) {
        this.salary = salary;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    }
    

    这是我的视图方法

      private void reloadButtonActionPerformed(java.awt.event.ActionEvent evt) {                                             
        try {
            ArrayList<Customer> customerList = null;
            try {
                try {
                    customerList = CustomerController.getAllCustomer();
                } catch (SQLException ex) {
                    Logger.getLogger(veiwCustomerFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
            } catch (Exception ex) {
                Logger.getLogger(ViewCustomerForm.class.getName()).log(Level.SEVERE, null, ex);
            }
            DefaultTableModel tableModel = (DefaultTableModel) customerTable.getModel();
            tableModel.setRowCount(0);
            for (Customer customer : customerList) {
                Object rowData[] = {customer.getId(), customer.getName(), customer.getAddress(), customer.getSalary()};
                tableModel.addRow(rowData);
            }
    
    
        } catch (Exception ex) {
            Logger.getLogger(ViewCustomerForm.class.getName()).log(Level.SEVERE, null, ex);
        }
    
    } 
    

    【讨论】:

      【解决方案2】:

      您必须在每次迭代中创建一个新的客户对象,然后在迭代的最后将该新创建的对象添加到 ArrayList 中。

      【讨论】:

        【解决方案3】:

        您正在重用customer 引用。 Java 通过引用为对象工作。不适用于基元。

        您正在做的是将相同的customer 添加到列表中,然后对其进行修改。从而为所有对象设置相同的值。这就是为什么你看到最后一个。因为都是一样的。

         while (rs.next()) {
                Customer customer = new Customer();
                customer.setId(rs.getInt("id"));
        
                ...
        

        【讨论】:

          【解决方案4】:

          尝试每次都创建新的客户实例,例如

                   while (rs.next()) {
          
                  Customer customer = new Customer();
                  customer.setId(rs.getInt("id"));
                  customer.setName(rs.getString("name"));
          
                  customer.setAddress(rs.getString("address"));
                  customer.setPhone(rs.getString("phone"));
                  customer.setEmail(rs.getString("email"));
                  customer.setBountPoints(rs.getInt("bonuspoint"));
                  customer.setTotalsale(rs.getInt("totalsale"));
          
                  customers.add(customer);
          
          
              }
          

          【讨论】:

            【解决方案5】:

            试试这个

            import java.sql.ResultSet;
            import java.util.ArrayList;
            
            import com.rcb.dbconnection.DbConnection;
            import com.rcb.model.Docter;
            
            
            public class DocterService {
            
            
            
            public ArrayList<Docter> getAllDocters() {
                ArrayList<Docter> docters = new ArrayList<Docter>();
            
                try {
                    String sql = "SELECT tbl_docters";
            
                    ResultSet rs = db.getData(sql);
                    while (rs.next()) {
                        Docter docter = new Docter();
            
                        docter.setD_id(rs.getInt("d_id"));
                        docter.setD_FName(rs.getString("d_fname"));
                        docter.setD_LName(rs.getString("d_lname"));
            
                        docters.add(docter);
            
                    }
            
                } catch (Exception e) {
                    System.out.println("getAllDocters()");
                    e.printStackTrace();
                }
            
                return (docters);
            }
            
            public static void main(String args[]) {
                DocterService ds = new DocterService();
                ArrayList<Docter> doctersList = ds.getAllDocters();
                String s[] = null;
                for (int i = 0; i < doctersList.size(); i++) {
            
                    System.out.println(doctersList.get(i).getD_id());
                    System.out.println(doctersList.get(i).getD_FName());
                }
            
              }
            }
            

            【讨论】:

              【解决方案6】:

              我正在尝试先从数据库中获取记录并存储在 ArrayList 中 但是当我在 html 页面上返回数组列表时,它只显示最后一条记录 重复作为我的数据库表的计数

              这部分大部分已经被之前的所有答案覆盖了。因此,您需要在while 循环中创建CustomerDTO 的新实例并将其添加到ArrayList

              还有一件事我想评论:

              • 确保在使用完所有资源后释放它们。从您发布的代码中,您尚未关闭您的 StatementConnection 对象(不确定您是否正在池化您的连接,在这种情况下,您需要释放此连接到游泳池)

              因此,当您考虑这些要点时,您的代码结构可能如下所示:

              public ArrayList<CustomerDTO> getAllCustomers() 
              {
                  ArrayList<CustomerDTO> customers = new ArrayList<CustomerDTO>();
                  Connection c = null;
                  Statement statement = null;
                  ResultSet rs        = null;
              
                  try {
                      c           = openConnection();
                      statement   = c.createStatement();
                      String s    = "SELECT * FROM customer";
              
                      rs          = statement.executeQuery(s);
                      int g =0;
              
                      while (rs.next()) {
                          CustomerDTO customer = new CustomerDTO();
                          //Code to fill up your DTO
                          customers.add(customer);
                      }
                  } catch (Exception e) {
                      System.out.println(e);
                  }finally{
                      //Code to release your resources
                  }
              
                  return customers;
              }
              

              【讨论】:

                【解决方案7】:

                如果您的客户类有静态变量,请将它们删除,这样您的类应该看起来像这样。

                public class customer {
                
                     private int id;
                     private String name;
                     private String DOB;
                
                    public int getId() {
                        return id;
                    }
                    public String getName() {
                        return name;
                    }
                    public String getDOB() {
                        return DOB;
                    }
                     public void setId(int id) {
                        this.id = id;
                    }
                    public void setName(String name) {
                        this.name = name;
                    }
                    public void setDOB(String dOB) {
                        this.DOB = dOB;
                    }
                

                而不是像

                public class customer {
                
                     private static int id;
                     private static String name;
                     private static String DOB;
                
                    public static int getId() {
                        return id;
                    }
                    public static String getName() {
                        return name;
                    }
                    public static String getDOB() {
                        return DOB;
                    }
                     public static void setId(int id) {
                        custumer.id = id;
                    }
                    public  static void setName(String name) {
                        customer.name = name;
                    }
                    public static void setDOB(String dOB) {
                        customer.DOB = dOB;
                    }
                

                【讨论】:

                  【解决方案8】:

                  Instead ofnull, use CustomerDTO customers =new CustomerDTO()`;

                  CustomerDTO customer = null;
                  
                  
                    private static List<Author> getAllAuthors() {
                      initConnection();
                      List<Author> authors = new ArrayList<Author>();
                      Author author = new Author();
                      try {
                          stmt = (Statement) conn.createStatement();
                          String str = "SELECT * FROM author";
                          rs = (ResultSet) stmt.executeQuery(str);
                  
                          while (rs.next()) {
                              int id = rs.getInt("nAuthorId");
                              String name = rs.getString("cAuthorName");
                              author.setnAuthorId(id);
                              author.setcAuthorName(name);
                              authors.add(author);
                              System.out.println(author.getnAuthorId() + " - " + author.getcAuthorName());
                          }
                          rs.close();
                          closeConnection();
                      } catch (Exception e) {
                          System.out.println(e);
                      }
                      return authors;
                  }
                  

                  【讨论】:

                    【解决方案9】:
                     while (rs.next()) {
                    
                                customer.setId(rs.getInt("id"));
                                customer.setName(rs.getString("name"));
                    
                                customer.setAddress(rs.getString("address"));
                                customer.setPhone(rs.getString("phone"));
                                customer.setEmail(rs.getString("email"));
                                customer.setBountPoints(rs.getInt("bonuspoint"));
                                customer.setTotalsale(rs.getInt("totalsale"));
                    
                                customers.add(customer);
                                 customer = null;
                            }
                    

                    尝试用上述代码替换您的 while 循环代码。这里我们所做的是在做customers.add(customer)之后我们在做customer = null;`

                    【讨论】:

                      【解决方案10】:

                      每次在while循环中创建CustomerDTO对象

                      检查以下代码

                          while (rs.next()) {
                      
                          Customer customer = new Customer();
                      
                          customer.setId(rs.getInt("id"));
                          customer.setName(rs.getString("name"));
                          customer.setAddress(rs.getString("address"));
                          customer.setPhone(rs.getString("phone"));
                          customer.setEmail(rs.getString("email"));
                          customer.setBountPoints(rs.getInt("bonuspoint"));
                          customer.setTotalsale(rs.getInt("totalsale"));
                      
                          customers.add(customer);
                      }
                      

                      【讨论】:

                        【解决方案11】:

                        此外,如果您希望结果集数据在列表中。请在 LOC 下方使用:

                        public List<String> dbselect(String query)
                          {
                              List<String> dbdata=new ArrayList<String>();
                              try {
                                dbResult=statement.executeQuery(query);
                                ResultSetMetaData metadata=dbResult.getMetaData();
                                for(int i=0;i>=metadata.getColumnCount();i++)
                                {
                                    dbdata.add(dbResult.getString(i));
                                }
                                return dbdata;
                            } catch (SQLException e) {
                                return null;
                            }
                              
                              
                          }
                        

                        【讨论】:

                          猜你喜欢
                          • 2016-07-01
                          • 2018-11-02
                          • 1970-01-01
                          • 2017-05-26
                          • 2012-06-21
                          • 2011-10-10
                          • 2021-03-26
                          • 2018-08-16
                          • 2019-12-20
                          相关资源
                          最近更新 更多