【问题标题】:result set returning only one row on executing the query结果集在执行查询时只返回一行
【发布时间】:2018-03-21 10:28:19
【问题描述】:

我试图通过 java 函数从数据库中检索数据。我的数据库中有超过 1 行,但结果集仅返回表的第一行。

public class checkoutDAOj {
    static Connection con=DBConnection.getConnection();
    static PreparedStatement ps=null;
    static ResultSet rs=null;
    static String stmnt;

    public static ArrayList<products> selectcart(String uname)
    {
        ArrayList<products> ap=ap=new ArrayList<>();
        products p=null;

        ps=null;
        rs=null;

        stmnt="select PID,P_QTY,P_SIZE from cart where uname=?";
        try {
            ps=con.prepareStatement(stmnt);
            ps.setString(1, uname);
            rs=ps.executeQuery();

            if(rs!=null)
            {
                int cou=0;
                while(rs.next())
                {
                    p=new products();
                    p.setPid(rs.getInt(1));
                    p.setP_quantity(rs.getInt(2));
                    p.setP_size(rs.getInt(3));
                    p=selectproduct(p);
                    ap.add(p);
                    p=null;
                    System.out.println(cou++);
                }
                System.out.println(ap);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return ap;
    }

    private static products selectproduct(products p)
    {

        ps=null;
        rs=null;
        stmnt="select p_name,p_image,p_price from Products where pid=?";
        try
        {
            ps=con.prepareStatement(stmnt);
            ps.setInt(1,p.getPid());
             rs=ps.executeQuery();
            if(rs!=null)
            {
                while(rs.next())
                {
                p.setName(rs.getString(1));
                p.setP_image(rs.getBlob(2));
                p.setP_price(rs.getDouble(3));
                }
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return p;
    }

}

我在这段代码中使用了两个函数来检索有关产品的完整信息。

我在 sqldeveloper

中使用 Oracle 作为 DB

【问题讨论】:

  • 是否有多行具有相同的 uname 列值?
  • 是的,它是我的外键,我有多个具有相同 uname 值的行

标签: java sql oracle jdbc resultset


【解决方案1】:

当您在selectproductprepareStatement 时,光标在selectcart 中的连接上关闭。你需要nStatementss,其中n是你要运行的查询数(这里你需要2)。此外,您不能明确地 null 共享 ResultSetPreparedStatement(s)。事实上,你也不能分享这些。

private static products selectproduct(products p)
{
    ps=null; // <-- ends the query in the other method.
    rs=null; // <-- ends the query in the other method.

【讨论】:

  • 我刚刚编辑了代码,我在这里粘贴了完整的 java 代码,即使我需要 N 连接,我也将连接用作全局变量??
  • 即使我删除了代码中的ps=null;rs=null; 结果是一样的并且没有变化@Elliot_Frisch
  • @nsuriya239 您不能共享这些变量。方法一获取一行,方法二获取 single 语句和结果集。这就是为什么你只能得到一排。
  • 它的工作谢谢@Elliot_Frisch
  • 请注意,启用自动提交可能会产生类似的效果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-30
  • 2018-12-31
  • 2017-09-10
  • 2015-10-14
  • 1970-01-01
  • 2020-12-08
  • 1970-01-01
相关资源
最近更新 更多