Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

java - jsp display random amount of rows from database

I'm making a web-application with JSP and Servlets and I came accross this problem: I have a table users and a myeducations table. These table relationship is established on user_id.

This is the table:

myeducation

----------------------------------------------------------------------------------
| ed_id | user_id | school_name | year_attended_from | year_attended_to | degree |
----------------------------------------------------------------------------------

Now, I want to display on a website (jsp) all of the user educations, but the number of educations user has is random: 1 user could have finished just 1 school, other could 3 and so on...

I understand how to retrieve just 1 row, the SQL is:

SELECT school_name 
FROM myeducation
INNER JOIN users ON users.user_id = myeducation.user_id;

But how to make this statement run in a loop, so that I get all the educations of a user, say if he has more than just 1. Then put them all in a session variable and display in a jsp's div.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You achieve this using joins or nested Query

As per your current DB Design, you can achieve this by a simple query itself, Since Education table holds the USER_ID

SELECT school_name FROM myeducation myedu where user_id="SOME_ID_HERE"

For looping String Array in servlet, simply do like this

ArrayList<String> arr = new ArrayList<String>();
while (rs.next()) {
  arr.add(rs.getString("school_name "));
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...