错误:在Java中开始结果集之前

Him*_*wal 0 java mysql database jdbc resultset

我知道这是一个愚蠢的问题,但我仍然需要这样做.这是java应用程序中的基本程序,我想同时使用3个查询来打印表.

(在这种情况下,我没有使用任何主键,所以请帮助我解决这个问题,而不要将我的属性作为主键 - 我知道这不是一个好习惯,但现在我需要完成它.)

我的代码:

    Connection con = null;        
    Statement stat1 = null, stat2 = null, stat3 = null;
    ResultSet rs1, rs2, rs3;
    stat1 = con.createStatement();
    stat2 = con.createStatement();
    stat3 = con.createStatement();

    String str = "\nProduct\tC.P\tS.P.\tStock\tExpenditure\tSales";
    info.setText(str);

    String s1 = "SELECT type, cp, sp, stock FROM ts_items GROUP BY type ORDER BY type";
    String s2 = "SELECT expenditure FROM ts_expenditure GROUP BY type ORDER BY type";
    String s3 = "SELECT sales FROM ts_sales GROUP BY type ORDER BY type";
    rs1 = stat1.executeQuery(s1);  
    rs2 = stat2.executeQuery(s2); 
    rs3 = stat3.executeQuery(s3); 

    String type;
    int cp, sp, stock, expenditure, sales;

   while( rs1.next() || rs2.next() || rs3.next() )
   {

       type = rs1.getString("type");
       cp = rs1.getInt("cp");
       sp = rs1.getInt("sp");
       stock = rs1.getInt("stock");

       expenditure = rs2.getInt("expenditure");

       sales = rs3.getInt("sales");

       info.append("\n" + type + "\t" + cp + "\t" + sp + "\t" + stock + "\t" + expenditure + "\t" + sales);


   }
Run Code Online (Sandbox Code Playgroud)

输出:

Runtime Exception: Before start of result set 
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 8

这就是问题:

while( rs1.next() || rs2.next() || rs3.next() )
Run Code Online (Sandbox Code Playgroud)

如果rs1.next()回报率true,rs2.next()rs3.next()不会被调用因短路.所以rs2,rs3都将在第一行之前.如果rs1.next()返回错误,那么无论如何你都无法读取...

我怀疑你真的想要:

while (rs1.next() && rs2.next() && rs3.next())
Run Code Online (Sandbox Code Playgroud)

毕竟,你只想继续前进,而所有三个结果集都有更多信息,对吧?

说实话,目前尚不清楚为什么你没有做适当的加入.这对我来说更有意义......那么你不会尝试在单个连接上使用多个结果集,并且你不会依赖type所有不同表中的完全相同的值.