views:

351

answers:

2

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.

A: 

Did you mean something like:

int i = 0;
ResultSet rs = stmt.executeQuery("select name from users");
while (rs.next()) {
    String name = rs.getString("name");
    names[i++] = name;
}
binil
This requires allocating the `names` array to the correct size. One way would be to execute a count() SQL statement first. I would recommend though using a collection (e.g. ArrayList).
Kevin Brock
pretty much. thats kinda what it started out likle. but i got rid of the loop until i could figure out how to take one row at a time.somethign liek this while(rs.next()) { int i = 0; contactListNames[i] = namesList.getString(i); System.out.println(" " + contactListNames[i]); }
OVERTONE
+2  A: 

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()]);
Kevin Brock
Or.. just stick to `List` instead of array. To the OP: learn [here](http://java.sun.com/docs/books/tutorial/collections/index.html) more about collection API.
BalusC
ive never used arraylist before. im havin trouble following the code there. ill give it a shot in a sec
OVERTONE
@BalusC: Agreed, no need for the array unless another API requires that.
Kevin Brock