Java SQL Exception Invalid Cursor State - no current row

北战南征 提交于 2019-12-04 08:03:00

You need to call ResultSet.next() before you can retrieve a column value.

// check if product code exists in database
try(Statement statement = connection.createStatement();
     ResultSet rs = statement.executeQuery("SELECT * FROM Products")){
if (rs.next()) // THIS is MISSING!
    String code =   rs.getString(1);

The above code would run without exceptions but would still fail logically since you're selecting all the products and just checking the code for the first one returned by the database. The correct way to check if the product already exists is

// check if product code exists in database
try(Statement statement = connection.createStatement();
    ResultSet rs = statement.executeQuery(
        "SELECT * FROM Products WHERE ProductCode = '" + p.getCode() + "'")){
if (rs.next()) {
   System.out.println("Error: This product is already in the database!");
   return;
}

In your insertProduct method, you need to call the next() method on your ResultSet before fetching data from it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!