简体   繁体   English

SQL中的问题,java中的ResultSet

[英]Problem with SQL, ResultSet in java

How can I iterate ResultSet ? 如何迭代ResultSet? I've tried with the following code, but i get the error java.sql.SQLException: Illegal operation on empty result set. 我已尝试使用以下代码,但我得到错误java.sql.SQLException:对空结果集的非法操作。

 while ( !rs.isLast()) {
     rs.next();
     int id = rs.getInt("person_id");
     SQL.getInstance().getSt().execute("INSERT ref_person_pub(person_id) VALUES(" + id + ")");
}

Update: I've found the problem. 更新:我发现了问题。 I have used only one statement from the SQL singleton. 我只使用了SQL单例中的一个语句。 When the statement is closed it can't be used again. 语句关闭后,不能再次使用。

As per the JDBC tutorial : 根据JDBC教程

resultSet = statement.executeQuery();
while (resultSet.next()) { 
    int id = resultSet.getInt("id");
    // ...
}

The ResultSet#next() moves the cursor forward one row from its current position and returns true if the new current row is valid. ResultSet#next()将光标从当前位置向前移动一行,如果新的当前行有效则返回true Thus, the while loop will stop automatically when there are no more rows. 因此,当没有更多行时, while循环将自动停止。

If it is supposed to return zero or one row instead of multiple rows, then rather use if instead: 如果它应该返回零行或一行而不是多行,那么改为使用if

resultSet = statement.executeQuery();
if (resultSet.next()) { 
    int id = resultSet.getInt("id");
    // ...
}

This way you have the opportunity to add an else . 这样您就有机会添加else

Update , that said and unrelated to the actual problem, I see more potential problems in your code: first, you seem to fire multiple queries which are dependent on each other. 更新 ,说和实际问题无关,我在你的代码中看到了更多的潜在问题:首先,你似乎触发了多个相互依赖的查询。 This can be done more efficient. 这可以更有效地完成。 Are you familiar with SQL Joins ? 你熟悉SQL连接吗? Second, aren't you leaking JDBC resources? 二,你是不是泄漏了JDBC资源? It look like that you're acquiring a statement, but not getting a handle of it so that you can properly close it after use. 看起来你正在获取一个声明,但没有掌握它,以便你可以在使用后正确关闭它。 Please consult the before linked JDBC tutorial for a basic explanation how to work properly with JDBC code and this article for several basic kickoff examples how to use JDBC properly. 请参阅链接的前JDBC教程基本说明如何使用JDBC代码和正常工作这篇文章的几个基本开球例子如何正确使用JDBC。 Otherwise your application may crash sooner or later when the DB runs out of resources. 否则,当数据库资源耗尽时,您的应用程序可能会迟早崩溃。

while(rs.next()) {
   // iterate
}

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

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