Domanda

Im using eclipse with the mysql library, i am trying to get a list of products from the database(there are only two), and it only return the first row. Why does the query only return one row? i think it might be something to do with wrong imports, i have no idea, im lost.

import java.sql.SQLException;
import java.util.ArrayList;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;


import classes.Product;

public class ProductDAO {

public ArrayList<Product> getProducts(){
    Connection connection = null;
    ResultSet resultSet;
    PreparedStatement statement;
    ArrayList<Product> products = new ArrayList();
    Connect con = new Connect();

    try{
        connection = con.connectTo();
        statement = (PreparedStatement) connection.prepareStatement("SELECT * FROM products ORDER BY sales DESC;");
        resultSet = statement.executeQuery();
        if(resultSet.next()){
            Product product = new Product();
            product.setName(resultSet.getString("name"));
            product.setMake(resultSet.getString("make"));
            product.setPrice(resultSet.getInt("price"));
            product.setDescription(resultSet.getString("description"));
            product.setCategory(resultSet.getString("category"));
            product.setSales(resultSet.getInt("sales"));
            product.setImage(resultSet.getString("image"));
            products.add(product);
        }
    }catch(SQLException ex){
        System.out.println(ex);
    }


    return products;
}
È stato utile?

Soluzione

You need to change:

if(resultSet.next()){

to

while(resultSet.next()){

resultSet.next() moves to the next row of data so you can then read it. It also returns true if there was a row or false if there wasn't.

Currently your code is just asking the resultset to get the first or or do nothing, whereas using the while will create a loop which will run until there are no more rows left. (or not run at all if there was none).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top