Grimeire Grimeire - 10 months ago 106
Java Question

Why do I get java.sql.SQLException: ResultSet not open. Operation 'next' not permitted. java derby database?

I'm getting this error:

java.sql.SQLException: ResultSet not open. Operation 'next' not
permitted. Verify that autocommit is off.

when I'm trying to create instances from a db.

Current code:

stmt = connection.createStatement();
results = stmt.executeQuery("SELECT * from animalTable");
int AnimalCat = -1;
//getting error on line below
int ID = results.getInt(1);
int Age = results.getInt(2);
String Name = results.getString(3);
String AType = results.getString(4);
String Breed = results.getString(5);
AnimalCat = results.getInt(6);
int Adoption = results.getInt(7);
String Gender = results.getString(8);
String Description = results.getString(9);
if(Gender == "Male"){
gen = true;

animal = new Animal(Age, AType, gen, Breed, Description, Name);
if(AnimalCat != -1){
ResultSet resultCat = stmt.executeQuery("SELECT * from CategoryTable where ID = " + AnimalCat);
//without this line below i get a cursor error;
System.out.println(resultCat.getInt(1) +"\n\n " + resultCat.getString(2));
String Category = resultCat.getString(2);
if(Category == "Lost"){
Date input = resultCat.getDate(3);
LocalDate date = input.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
ResultSet personData = stmt.executeQuery("SELECT * from PersonTable where ID = " + resultCat.getInt(4));
Person person = new Person(personData.getString(2), personData.getString(3), personData.getString(4), personData.getString(5));
Category lost = new Lost(date, resultCat.getString(5), person);
catch (SQLException sqlExcept)

I have tried turning off auto commit like it says in the exception and also adding a finally block and closing the statement. From what I can see online that fixed others issues but no luck with mine.

I know the;
is behind the error somehow but I get an "Invalid cursor state - no current row" without it


You have a Statement, obtain a ResultSet from the statement, then obtain another ResultSet. This automatically closes the first ResultSet:

By default, only one ResultSet object per Statement object can be open at the same time. Therefore, if the reading of one ResultSet object is interleaved with the reading of another, each must have been generated by different Statement objects. All execution methods in the Statement interface implicitly close a statment's current ResultSet object if an open one exists.

So when you call next on the first ResultSet an exception is raised. The Javadoc also tells you what to change: Create a second statement and use that to obtain the second ResultSet.