Storing Result set into an array

OVERTONE picture OVERTONE · Apr 23, 2010 · Viewed 67.2k times · Source

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.

Answer

Kevin Brock picture Kevin Brock · Apr 23, 2010

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()]);