简体   繁体   English

java.sql-ResultSet r.next()不起作用

[英]java.sql - ResultSet r.next() doesn't work

I don't understand why ResultSet isn't working as if there are no results 我不明白为什么ResultSet无法正常工作,好像没有结果一样

public static int checkProductID(Connection conn) {

    boolean productIDisvalid = false;
    int id = 0;
    while (!productIDisvalid) {
        System.out.println("Enter a product ID: ");
        try {
            id = Integer.parseInt(readLine());
            if (id < 10000000 && id > 0) {
                System.out.println(id);
                // PreparedStatement pstmt = conn.prepareStatement ("INSERT INTO INVENTORY VALUES (?,?,?,?) ");
                // pstmt.setInt(1,4000); pstmt.setString(2,"hello"); pstmt.setInt(3,4000); pstmt.setInt(4,400);
                PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM INVENTORY WHERE PRODUCTID = ?");
                pstmt.setInt(1, id);
                ResultSet r = pstmt.executeQuery();
                while (r.next()) {
                    System.out.println(r.getInt("PRODUCTID"));
                    if (r.getInt("PRODUCTID") == id) return id;
                }
            }

        } catch (NumberFormatException | SQLException | NullPointerException e) {
            e.printStackTrace();
            continue;
        }
    }

    return id;
}

I quoted out an insert values to prove it works and that it is correctly connected to the database. 我引用了一个插入值来证明它可以正常工作,并且已正确连接到数据库。

在此处输入图片说明

The insert values works. 插入值起作用。 But whenever I attempt to perform a search query on the database, it doesn't work, r.next() is never true and the print statement inside that while loop never executes, even if I change the query to "SELECT * FROM INVENTORY WHERE PRODUCTID = 1000" 但是,每当我尝试对数据库执行搜索查询时,它都不会起作用,即使我将查询更改为“ SELECT * FROM INVENTORY”,r.next()也永远不会为true,并且while循环中的print语句也不会执行。 PRODUCTID = 1000“

Your problem was happening because you had not explicitly committed your insert from sqlplus. 发生问题是因为您没有明确地从sqlplus提交插入。 When you exit sqlplus there is an implicit commit that happens which is why the problem went away. 退出sqlplus时,会发生隐式提交,这就是问题消失的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM