2

I am having many rows in table and I ran the same query on my database which is MySql but java ResultSet is only giving the first row of the table. Here is my code.

public ArrayList<String> getAllAlbumsName(Integer uid) {
    ArrayList<String>allAlbumsName = new ArrayList<String>();
    try {
        String qstring = "SELECT albumname FROM picvik_picture_album WHERE " +
                "uid = '" + uid + "';";

        System.out.println(qstring);
        connection = com.picvik.util.MySqlConnection.getInstance().getConnection();
        ptmt = connection.prepareStatement(qstring);
        resultSet = ptmt.executeQuery();
        if(resultSet.next()) {
            System.out.println(resultSet.getString("albumname"));
            allAlbumsName.add(resultSet.getString("albumname"));
        }

        resultSet.close();
        ptmt.close();
        connection.close();


    } catch (Exception e) {
        e.printStackTrace();
    }   
    return allAlbumsName;
}
Ananda
  • 1,572
  • 7
  • 27
  • 54

3 Answers3

13
if(resultSet.next()) {
            System.out.println(resultSet.getString("albumname"));
            allAlbumsName.add(resultSet.getString("albumname"));
        }

If you would like to get all rows, it should be:

while(resultSet.next()) {
        System.out.println(resultSet.getString("albumname"));
        allAlbumsName.add(resultSet.getString("albumname"));
    }

The while statement continually executes a block of statements while a particular condition is true

Note: As @BalusC commented, your code would introduce SQL Injection attack, it is better to use ptmt.set... Instead of constructing SQL String manually.

kosa
  • 65,990
  • 13
  • 130
  • 167
3

try while(resultSet.next()) {

instead of if (resultSet.next()) {

Skip Head
  • 7,580
  • 1
  • 30
  • 34
2

Change if (resultSet.next()) { to while (resultSet.next()) {

hd1
  • 33,938
  • 5
  • 80
  • 91