13

大家好,我想在 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;
}
4

11 回答 11

15

尝试使用以下代码

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);
    }

} 
于 2014-09-11T01:59:03.213 回答
4

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

于 2012-08-16T08:50:24.487 回答
1

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

         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);


    }
于 2012-08-16T08:54:58.563 回答
1

您正在重用customer参考。Java 通过引用为对象工作。不适用于原始人。

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

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

        ...
于 2012-08-16T08:50:04.033 回答
1

尝试这个

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());
    }

  }
}
于 2018-03-18T10:31:44.363 回答
0

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;
}
于 2015-02-06T05:48:19.423 回答
0

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

这部分大部分已被所有先前的答案所涵盖。因此,您需要CustomerDTOwhile循环中创建一个新实例并将其添加到您的ArrayList.

我还想评论一件事:

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

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

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;
}
于 2012-08-16T09:18:25.933 回答
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);
             customer = null;
        }

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

于 2015-02-19T12:31:58.693 回答
0

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

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;
    }
于 2014-03-27T13:39:21.460 回答
0

每次在 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);
}
于 2017-12-13T13:52:12.787 回答
0

此外,如果您希望结果集数据在列表中。请在 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;
    }
      
      
  }
于 2020-07-26T10:25:14.513 回答