我收到了这个错误:
java.sql.SQLException:ResultSet未打开。操作'下一步'不是 允许的。验证自动提交是否已关闭。
当我尝试从db创建实例时。
当前代码:
try
{
connection.setAutoCommit(false);
stmt = connection.createStatement();
results = stmt.executeQuery("SELECT * from animalTable");
int AnimalCat = -1;
System.out.print(connection.getAutoCommit());
//getting error on line below
while(results.next())
{
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);
animalList.add(animal);
if(AnimalCat != -1){
ResultSet resultCat = stmt.executeQuery("SELECT * from CategoryTable where ID = " + AnimalCat);
//without this line below i get a cursor error
resultCat.next();
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);
animal.setAnimalCat(lost);
personList.add(person);
}
}
}
results.close();
stmt.close();
}
catch (SQLException sqlExcept)
{
sqlExcept.printStackTrace();
}
我尝试关闭自动提交,就像在异常中说的那样,并添加了一个finally块并关闭了语句。从我在网上看到的那个修复了其他问题但我没有运气的事情。
我知道resultCat.next();
在某种程度上是错误的背后但是我得到了一个“无效的游标状态 - 没有它的当前行”
答案 0 :(得分:4)
您有Statement
,从语句中获取ResultSet
,然后获取另一个ResultSet
。这会自动closes第一个ResultSet
:
默认情况下,每个Statement对象只能打开一个ResultSet对象 同时。因此,如果读取一个ResultSet对象是 与另一个的读取交错,每个必须已经生成 通过不同的Statement对象。 Statement中的所有执行方法 如果是,接口隐式关闭一个语句的当前ResultSet对象 打开一个。
因此,当您在第一个ResultSet上调用next
时,会引发异常。 Javadoc还告诉您要更改的内容:创建第二个语句并使用它来获取第二个ResultSet。