yashhy
yashhy

Reputation: 3086

resultset to get values from next row

hi i'm new to java how ever i googled and got code to connect to database and retrieve the values.

the problem is ResultSet gets the value only from FIRST ROW of the table

here is the code..

String stmt = "select * from tablename";
ResultSet resultSet = statement.executeQuery(stmt);
while(resultSet.next())
 {
    String val = resultSet.getString(3);
    System.out.println(val);
 } 

it returns only the 3rd value (because i have mentioned that and i need that column value only) of the first row, but i need to get the every 3rd value (column) of every row and store it in a array.

Upvotes: 2

Views: 4350

Answers (1)

Nathan Hughes
Nathan Hughes

Reputation: 96385

The code you have posted should already be getting the 3rd value in each row. There's nothing obviously wrong with what you've shown. It's just a matter of trying different things and figuring out what it is that you think you know that isn't true.

Verify the query works by itself in a SQL client like Squirrel or whatever you have handy.

Add printlns or logging to verify you're actually executing the part of the code that has the query.

Add some text to the println in your code so that if the value is blank you'll still see something get written.

Change the query to state the column explicitly instead of leaning on *, so it reads like select mystuff from tablename, and see if you can make that query work.

Once you are ready to add the part where you store the values, you would be better off using an ArrayList than an array, because the list will resize as you add things to it. ArrayList is backed by an array, the ArrayList takes care of the resizing for you. If you really do need an array you can call the toArray method on the list to create one once it's populated. So it would look like:

List<String> list = new ArrayList<String>();
while(resultSet.next())
{
    String val = resultSet.getString(3);
    list.add(val);
    System.out.println(val);
}
String[] vals = list.toArray(new String[] {});

Upvotes: 1

Related Questions