JDBC ResultSet is giving only one row although there are many rows in table?
java, jdbc
Solution
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.
Problem
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; } ```