Reputation: 51
I'm trying to fetch records from MySQL database in a java class, and the first
entry isn't getting fetched.
Here is the class in which I'm trying to fetch the records :
public class BookDaoImpl
{
private static String SELECT;
static
{
SELECT = "SELECT * FROM databaseName.books;";
}
public BookDaoImpl()
{
connection = JDBCDaoImpl.getConnection();
}
public List<Book> fetchBooksList() throws SQLException
{
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(SELECT);
if (!resultSet.next())
return null;
List<Book> listOfBooks = new ArrayList<Book>();
Book tempBook;
while (resultSet.next())
{
tempBook = new Book();
tempBook.setBookId(resultSet.getInt("bookId"));
tempBook.setBookName(resultSet.getString("bookName"));
tempBook.setBookPrice(resultSet.getInt("bookPrice"));
tempBook.setBookQuantity(resultSet.getInt("bookQuantity"));
listOfBooks.add(tempBook);
}
System.out.println("listOfBooks : ");
for (int i = 0; i < listOfBooks.size(); i++)
{
System.out.println(listOfBooks.get(i));
}
return listOfBooks;
}
}
Also, even if I add a few more entries to the table, the first entry still doesn't come.
Upvotes: 1
Views: 92
Reputation: 2070
You skip the first entry here:
if (!resultSet.next())
return null;
If you delete these two rows of code, your method will work fine (but return an empty list instead of null, in the case no entries exist).
Upvotes: 5