JDBC ResultSet is giving only one row although the

2020-02-15 06:54发布

问题:

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;
}

回答1:

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.



回答2:

try while(resultSet.next()) {

instead of if (resultSet.next()) {



回答3:

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



标签: java jdbc