Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ResultSet to Array

Tags:

java

android

jdbc

I have a Result set returned using a query:

String query = "select Bookname, SubjectName from books join Subjects on Subjects.SubjectID = Books.subjectID where classID = '1a'";
ResultSet temp = null;
try
{
   Statement st = conn.createStatement();
   ResultSet rs = st.executeQuery(query);

   temp = rs;
}

I was just wondering is it possible to turn the Resultset into two seperate arrays: eg BookName[] and BookSubject[] so I can show them in a list view later on? Relatively new to resultset and this concept in android

like image 325
Eoin Ó Cribín Avatar asked Mar 14 '23 05:03

Eoin Ó Cribín


1 Answers

You should be able to easily iterate through the results on the result set, populating each array with the results as you interate.

Something like this:

...
ResultSet rs = st.executeQuery(query);

ArrayList<String> names = new ArrayList<String>();
ArrayList<String> subjects = new ArrayList<String>();

while (rs.next()) { 
    names.add(rs.getString(1));
    subjects.add(rs.getString(2));
}

// finally turn the array lists into arrays - if really needed
String[] nameArr = new String[names.size()];
nameArr = names.toArray(nameArr);

String[] subjectArr = new String[subjects.size()];
subjectArr = subjects.toArray(subjectArr);

Hope that helps!

like image 173
Davi Cavalcanti Avatar answered Mar 25 '23 06:03

Davi Cavalcanti