我将eclipse与mysql库一起使用,我试图从数据库中获得产品列表(只有两个),并且它仅返回第一行。
为什么查询只返回一行?我认为这可能与进口错误有关,我不知道,我输了。

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

最佳答案

您需要更改:

if(resultSet.next()){




while(resultSet.next()){


resultSet.next()移至下一行数据,以便随后可以读取它。如果存在一行,则返回true;否则返回false。

当前,您的代码只是要求结果集获得第一个或不执行任何操作,而使用while将创建一个循环,该循环将运行直到没有剩余的行为止。 (如果没有,则完全不运行)。

关于mysql - MySQL Select仅从Eclipse返回一行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23107092/

10-12 00:23
查看更多