2015-04-06 73 views
0

添加和检索使用主键MySQL数据库数据我有一个MySQL表像这样通过的ArrayList JAVA

create table students(id varchar(20), 
name varchar(20), 
address varchar(255) 
primary key(id)); 

我想用他的jsp.I唯一的ID已经试过这样

显示每个学生数据
ArrayList<Object> student = new ArrayList<Object>(); 

     try { 
      DB_Conn con = new DB_Conn(); 
      Connection c = con.getConnection(); 
      Statement statement = c.createStatement() ; 
      ResultSet resultset = statement.executeQuery("select * from students"); 
      while(resultset.next()){ 
       student.add(resultset.getString(1)); 
       student.add(resultset.getString(2)); 
       student.add(resultset.getString(3)); 
      } 
     } catch (SQLException e){ 
       System.out.println(e.getMessage()); 
     } 
     return student; 

现在我想显示每个学生的姓名和地址,使用他们唯一的ID。如何表述。我怎样才能从arraylist检索特定的变量数据。

+2

不是直接将不同的值插入到数组列表中,而是在Arraylist中创建学生和对象的对象,然后再回顾学生的对象。 – Pratik 2015-04-06 07:00:40

回答

0

尝试使具有Studentidnameaddress因为它的属性,然后代替ArrayList中添加属性的,你应该添加Student对象

ArrayList<Student> studentList=new ArrayList<Student>(); 
String id=resultset.getString(1); 
String name=resultset.getString(2); 
String address=resultset.getString(3); 
Student st=new Student(id,name.address); 
studentList.add(st); 

要显示在JSP一样,你可以使用

<c:forEach var="i" items="${studentList}> 
    ${i.name}<br>${i.id}<br>${i.address} 
</c:forEach> 
0

有做到这一点,最常见多发的方法是

使用两个不同的ArrayList来存储学生

ArrayList<Object> nameList= new ArrayList<Object>(); 
ArrayList<Object> addressList= new ArrayList<Object>(); 

的名称&地址,并在particuler值INT使用 -

nameList.add(resultset.getString(2)); 
addressList.add(resultset.getString(3)); 

nameList.get(i) & addressList.get(i)会给你造成特定学生的。