从arraylist中的存储数据中读取数据

时间:2015-02-20 14:25:55

标签: java jdbc arraylist

有人可以帮助我,我有这些类,我想读出getAllCustomer(),但我不知道如何在我的main方法中实现它。 我已经尝试了几件事,但效果不好。谁能帮我? :P

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 Customer (String pId, String pName, String pSalary, String pAddress) {
        id = pId;
        name = pName;
        salary = pSalary;
        adress = pAddress;

    }

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

2 个答案:

答案 0 :(得分:0)

假设你的getAllCustomer()方法在A类中。然后在您的main方法中,您执行以下操作

public void main(String[] args){
 List<Customer> customers =  A.getAllCustomer();
}

根据您问题的性质this JDBC tutorial will help you

答案 1 :(得分:0)

您的Salary字段的数据类型是String,但您获得的值为double。

您需要做的就是将rst.getDouble(&#34; salary&#34;)更改为rst.getString(&#34; salary&#34;)

调用方法:

public static void main(String[] args)

  ArrayList<Customer> customers = YourDALClass.getAllCustomer();
  for(Customer c : customers){
     System.out.println(c.getName());
  }
}