SQL中的问题,Java中的ResultSet [英] Problem with SQL, ResultSet in java

查看:108
本文介绍了SQL中的问题,Java中的ResultSet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何迭代ResultSet?我尝试使用以下代码,但出现错误java.sql.SQLException:对空结果集的非法操作.

How can I iterate ResultSet ? I've tried with the following code, but i get the error java.sql.SQLException: Illegal operation on empty result set.

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

更新:我发现了问题.我仅使用了SQL单例中的一条语句.语句关闭后,将无法再次使用.

Update: I've found the problem. I have used only one statement from the SQL singleton. When the statement is closed it can't be used again.

推荐答案

按照

ResultSet#next() 将光标从其当前位置向前移动一行,如果新的当前行有效,则返回true.因此,while循环将在没有更多行时自动停止.

The ResultSet#next() moves the cursor forward one row from its current position and returns true if the new current row is valid. Thus, the while loop will stop automatically when there are no more rows.

如果应该返回零或一行而不是多行,则应使用if代替:

If it is supposed to return zero or one row instead of multiple rows, then rather use if instead:

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

这样,您就有机会添加else.

This way you have the opportunity to add an else.

更新,它与实际问题无关,我发现您的代码中存在更多潜在问题:首先,您似乎触发了多个相互依赖的查询.这可以更有效地完成.您是否熟悉 SQL连接?其次,您不是在泄漏JDBC资源吗?看起来您正在获取一条语句,但没有得到它的句柄,因此您可以在使用后正确将其关闭.请参考之前链接的JDBC教程,以获取有关如何正确使用JDBC代码和

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? Second, aren't you leaking JDBC resources? 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. Otherwise your application may crash sooner or later when the DB runs out of resources.

这篇关于SQL中的问题,Java中的ResultSet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆