Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing Result set into an array

i know this should be simpel and im probably staring straight at the problem but once again im stuck and need the help of the code gurus.

im trying too take one row from a column in jdbc, and put them in an array.

i do this as follows:

public void fillContactList()
       {
           createConnection();
           try
           {
               Statement stmt = conn.createStatement();
               ResultSet namesList = stmt.executeQuery("SELECT name FROM Users");
               try
               {
                   while (namesList.next())
                   {
                       contactListNames[1] = namesList.getString(1);
                       System.out.println("" + contactListNames[1]);
                   }   
               }
               catch(SQLException q)
               {

               }
               conn.commit();
               stmt.close();
               conn.close();
           }
           catch(SQLException e)
           {

           }

creatConnection is an already defined method that does what it obviously does. i creat my result set while theres another one, i store the string of that column into an array. then print it out for good measure. too make sure its there.

the problem is that its storing the entire column into contactListNames[1]

i wanted to make it store column1 row 1 into [1]

then column 1 row 2 into [2]

i know i could do this with a loop. but i dont know too take only one row at a time from a single column. any ideas?

p.s ive read the api, i jsut cant see anything that fits.

like image 844
OVERTONE Avatar asked Apr 23 '10 15:04

OVERTONE


People also ask

Can we return ResultSet?

Yes, just like any other objects in Java we can pass a ResultSet object as a parameter to a method and, return it from a method.

Can you store methods in an array?

In Java, arrays are objects. All methods of class object may be invoked in an array. We can store a fixed number of elements in an array.


1 Answers

You should use an ArrayList which provides all the logic to automatically extend the array.

List rowValues = new ArrayList();
while (namesList.next()) {
    rowValues.add(namesList.getString(1));
}   
// You can then put this back into an array if necessary
contactListNames = (String[]) rowValues.toArray(new String[rowValues.size()]);
like image 193
Kevin Brock Avatar answered Sep 24 '22 00:09

Kevin Brock