从数据库读取数据并存储在Array List对象中

时间:2012-08-16 08:46:53

标签: java jdbc

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

11 个答案:

答案 0 :(得分:10)

尝试使用以下代码

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

} 

答案 1 :(得分:4)

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

答案 2 :(得分: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);


    }

答案 3 :(得分: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());
    }

  }
}

答案 4 :(得分:0)

您正在重复使用customer参考。 Java通过引用为Obejcts工作。不适用于原语。

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

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

        ...

答案 5 :(得分:0)

  

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

这一部分大部分都被以前的所有答案所涵盖。因此,您需要在CustomerDTO循环中创建while的新实例,并将其添加到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;
}

答案 6 :(得分: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;
    }

答案 7 :(得分:0)

Instead of null , use CustomerDTO customers =新的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;
}

答案 8 :(得分: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)之后我们正在做客户= null;`

答案 9 :(得分:0)

  

每次在循环中创建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);
}

答案 10 :(得分: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;
    }
      
      
  }