Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
780 views
in Technique[技术] by (71.8m points)

jdbc - Even though my RESULTSET is not empty I am not getting output. Using JAVA AND ORACLE DB

The database has the same format of date. Query is working fine in Oracle DB. In java the resultset is not empty. Cannot think of the possible reason for this problem. Please help.

try {
            Class.forName(driverClass);
            Connection cn=null;
            cn=DriverManager.getConnection(url,username,password);
            Scanner sc=new Scanner(System.in);
            
            
            System.out.print("Enter Ship date in yyyy-mon-dd format: ");
            String str=sc.next();  
            System.out.println(str);

            //select PO_NUMBER from PURCHASE_ORDER where SHIPDATE=TO_DATE('2021-JAN-25','YYYY-MON- 
            DD');
            String sql = "select PO_NUMBER from PURCHASE_ORDER where 
            SHIPDATE=TO_DATE('"+str+"','YYYY-MON-DD')";
            System.out.println("Query exec");
            Statement stmt = cn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            if(rs.next())
                System.out.println("Purchase Order Shipped on "+ str+" are: ");
            else
                System.out.println("empty rs");
            while(rs.next()) {
                System.out.println(rs.getInt(1));                   
            }
            cn.close();
            
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }

 OUTPUT : Enter Ship date in yyyy-mon-dd format: 2021-JAN-25
 2021-JAN-25
 Query exec
 Purchase Order Shipped on 2021-JAN-25 are: 
question from:https://stackoverflow.com/questions/65910421/even-though-my-resultset-is-not-empty-i-am-not-getting-output-using-java-and-or

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your current while loop discards the first row (which is presumably the only row). Easiest solution I can see would be to change it to a do while in the if. Something like,

if(rs.next()) {
    System.out.println("Purchase Order Shipped on " + str + " are: ");
    do {
        System.out.println(rs.getInt(1));                   
    } while(rs.next());
} else {
    System.out.println("empty rs");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...